package com.boruan.shengtangfeng.core.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boruan.shengtangfeng.core.dao.*;
import com.boruan.shengtangfeng.core.dto.*;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.enums.QuestionType;
import com.boruan.shengtangfeng.core.service.IClassAndService;
import com.boruan.shengtangfeng.core.service.IClassTeacherService;
import com.boruan.shengtangfeng.core.tencentEntity.CreateGroupReturn;
import com.boruan.shengtangfeng.core.utils.*;
import com.boruan.shengtangfeng.core.vo.*;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.VideoVoMapper;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author guojiang
 * @projectName ShengTangFeng-V2-JAVA
 * @description: v4E 班级-教师端
 * @date 2021/4/7 9:20
 */
@Service
@Transactional(readOnly = false)
public class ClassTeacherServiceImpl implements IClassTeacherService {

    @Autowired
    private IUserDao userDao;
    @Autowired
    private ISchoolDao schoolDao;
    @Autowired
    private IClassAndDao classAndDao;
    @Autowired
    private IClassMembersDao classMembersDao;
    @Autowired
    private IGroupChatDao groupChatDao;
    @Autowired
    private IGroupMembersDao groupMembersDao;
    @Autowired
    private IClassInformDao classInformDao;
    @Autowired
    private InformDao informDao;
    @Autowired
    private IJobDao jobDao;
    @Autowired
    private ISubjectDao subjectDao;
    @Autowired
    private IUserJobDao userJobDao;
    @Autowired
    private IJobQuestionDao jobQuestionDao;
    @Autowired
    private IQuestionDao questionDao;
    @Autowired
    private IQuestionRecordDao questionRecordDao;
    @Autowired
    private IVideoDao videoDao;
    @Autowired
    private IClassJobDao classJobDao;
    @Autowired
    private IClassAndService classAndService;
    @Autowired
    private IUserFriendAndBlacklistDao userFriendAndBlacklistDao;
    @Autowired
    private ChineseInital chineseInital;
    @Autowired
    private IFavoritesQuestionDao favoritesQuestionDao;
    @Autowired
    private IGradeDao gradeDao;
    @Autowired
    private IModuleDao moduleDao;
    @Autowired
    private IJobNameDao jobNameDao;
    @Autowired
    private IClassParameterDao classParameterDao;
    @Autowired
    private VideoService videoService;
    @Autowired
    private IJobParameterDao jobParameterDao;
    @Autowired
    private IJobBackDao jobBackDao;
    @Autowired
    private IClassInformMemberDao classInformMemberDao;
    @Autowired
    private IClassVideoMemberDao classVideoMemberDao;
    @Autowired
    private IKickOutDao kickOutDao;
    @Autowired
    private IJobBackDeletedDao jobBackDeletedDao;
    @Autowired
    private TencentUtil tencentUtil;
    @Autowired
    private ALiYunUtils aLiYunUtils;


    /**
     * 获取省
     *
     * @return
     */
    @Override
    public GlobalReponse<AddressDto> getProvince() {
        List<AddressDto> allProvince = schoolDao.getAllProvince();
        return GlobalReponse.success(allProvince);
    }

    /**
     * 获取市
     *
     * @return
     */
    @Override
    public GlobalReponse<AddressDto> getCity(Long provinceId) {
        List<AddressDto> allCity = schoolDao.getAllCity(provinceId);
        return GlobalReponse.success(allCity);
    }

    /**
     * 获取区
     *
     * @return
     */
    @Override
    public GlobalReponse<AddressDto> getCounty(Long cityId) {
        List<AddressDto> allCounty = schoolDao.getAllCounty(cityId);
        return GlobalReponse.success(allCounty);
    }

    /**
     * 根据地址查询学校
     *
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<School>> findSchool(FindSchoolDto dto) {
        PageQuery<School> query = new PageQuery<>();
        query.setPageNumber(dto.getPageNo());
        query.setPageSize(10);
        query.setPara("province", dto.getProvince());
        query.setPara("city", dto.getCity());
        query.setPara("county", dto.getCounty());
        if (dto.getName() != null && !dto.getName().equals("")) {
            query.setPara("name", dto.getName());
        }
        schoolDao.findSchoolPage(query);
        if (query.getList().isEmpty()) {
            return GlobalReponse.success("暂无学校");
        }
        return GlobalReponse.success(query);
    }

    /**
     * 创建学校
     *
     * @param schoolDto
     * @return
     */
    @Override
    public GlobalReponse<School> createSchool(Long userId, SchoolDto schoolDto) {
        School single = schoolDao.createLambdaQuery().andEq(School::getName, schoolDto.getSchoolName()).andEq(School::getIsDeleted, 0).single();
        if (single != null) {
            return GlobalReponse.fail("该学校名称已存在");
        }
        School school = new School();
        school.setName(schoolDto.getSchoolName());
        String provinceName = schoolDao.getProvince(schoolDto.getProvinceId());
        String cityName = schoolDao.getCity(schoolDto.getCityId());
        String countyName = schoolDao.getCounty(schoolDto.getCountyId());
        school.setProvince(provinceName);
        school.setCity(cityName);
        school.setCounty(countyName);
        school.setCreateBy(userId.toString());
        school.setType(0);
        school.setCreateTime(new Date());
        school.setIsDeleted(false);
        schoolDao.insertTemplate(school);
        return GlobalReponse.success("创建成功").setData(school);
    }


    /**
     * 创建班级
     *
     * @param userId
     * @param classDto
     * @return
     */
    @Override
    public GlobalReponse<ClassAndVo> createClass(Long userId, ClassAndDto classDto) {
        String schoolYeardto = classDto.getSchoolYear();
        ClassAnd single = classAndDao.createLambdaQuery().andEq(ClassAnd::getSchoolId, classDto.getSchoolId()).andEq(ClassAnd::getGradeDivision, classDto.getGradeDivision()).andEq(ClassAnd::getSchoolYear, schoolYeardto.substring(0, 4)).andEq(ClassAnd::getName, classDto.getName()).andEq(ClassAnd::getIsDeleted, false).single();
        if (single != null) {
            ClassAndVo vo = new ClassAndVo();
            User user = userDao.unique(Long.valueOf(single.getCreateBy()));
            School school = schoolDao.unique(single.getSchoolId());
            vo.setCreateId(user.getId());
            vo.setCreateName(user.getName());
            vo.setCreateImage(user.getHeadImage());
            vo.setSchoolId(school.getId());
            vo.setProvince(school.getProvince());
            vo.setCity(school.getCity());
            vo.setCounty(school.getCounty());
            vo.setSchoolName(school.getName());
            vo.setClassId(single.getId());
            vo.setClassName(single.getName());
            vo.setClassNum(single.getClassNum());
            vo.setSchoolYear(single.getSchoolYear() + "级");
            long count = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, single.getId()).andEq(ClassMembers::getIsDeleted, false).count();
            vo.setMemberNum(count);
            GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, single.getId()).andEq(GroupChat::getIsDeleted, false).single();
            if (groupChat.getTencentId() != null) {
                vo.setTencentId(groupChat.getTencentId());
            }

            //获取学年配置
            ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
            int year = Integer.valueOf(single.getSchoolYear());
            //判断学制
            int num = classParam.getEducationSystem() == 1 ? 5 : 6;
            //判断上下学期
            String now = new SimpleDateFormat("MM-dd").format(new Date());
            String spring = classParam.getSpringTime();
            String autumn = classParam.getAutumnTime();
            int newYear = year + 1;
            String nowTime = year + "-" + now;
            String springTime = year + "-" + spring;
            String autumnTime = newYear + "-" + autumn;
            Date date = null;
            Date date1 = null;
            Date date2 = null;
            String item = null;
            try {
                date = DateUtils.parseDate(nowTime, "yyyy-MM-dd");
                date1 = DateUtils.parseDate(springTime, "yyyy-MM-dd");
                date2 = DateUtils.parseDate(autumnTime, "yyyy-MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (date.after(date1) && date.before(date2)) {
                item = "上";
            } else {
                item = "下";
            }
            Calendar cal = Calendar.getInstance();
            int yearD = cal.get(Calendar.YEAR);
            vo.setGradeName(NumberUtils.int2chineseNum(yearD - year + 1) + "年级" + item);
            vo.setClassStatus(single.getStatus());
            return GlobalReponse.success("班级已被创建").setData(vo);
        }
        ClassAnd classAnd = new ClassAnd();
        BeanUtils.copyProperties(classDto, classAnd);
        User user = userDao.unique(userId);

        String schoolYear = classDto.getSchoolYear();
        classAnd.setSchoolYear(schoolYear.substring(0, 4));
        classAnd.setClassNum(this.getSixRandom());
        classAnd.setCreateBy(userId.toString());
        classAnd.setStatus(0);
        classAnd.setCreateTime(new Date());
        classAnd.setIsDeleted(false);
        classAndDao.insertTemplate(classAnd, true);
        ClassMembers classMembers = new ClassMembers();
        classMembers.setClassId(classAnd.getId());
        classMembers.setNickname(user.getName());
        classMembers.setUserId(userId);
        classMembers.setType(3);
        classMembers.setCreateBy(userId.toString());
        classMembers.setCreateTime(new Date());
        classMembers.setIsDeleted(false);
        classMembersDao.insertTemplate(classMembers, true);
        ClassAndVo vo = new ClassAndVo();
        School school = schoolDao.unique(classDto.getSchoolId());
        vo.setCreateId(user.getId());
        vo.setCreateName(user.getName());
        vo.setCreateImage(user.getHeadImage());
        long count = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classAnd.getId()).andEq(ClassMembers::getIsDeleted, false).count();
        vo.setMemberNum(count);
        vo.setSchoolId(school.getId());
        vo.setProvince(school.getProvince());
        vo.setCity(school.getCity());
        vo.setCounty(school.getCounty());
        vo.setSchoolName(school.getName());
        vo.setClassId(classAnd.getId());
        vo.setClassName(classAnd.getName());
        vo.setClassNum(classAnd.getClassNum());
        vo.setSchoolYear(classAnd.getSchoolYear() + "级");
        //获取学年配置
        ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
        int year = Integer.valueOf(classAnd.getSchoolYear());
        //判断学制
        int num = classParam.getEducationSystem() == 1 ? 5 : 6;
        //判断上下学期
        String now = new SimpleDateFormat("MM-dd").format(new Date());
        String spring = classParam.getSpringTime();
        String autumn = classParam.getAutumnTime();
        int newYear = year + 1;
        String nowTime = year + "-" + now;
        String springTime = year + "-" + spring;
        String autumnTime = newYear + "-" + autumn;
        Date date = null;
        Date date1 = null;
        Date date2 = null;
        String item = null;
        try {
            date = DateUtils.parseDate(nowTime, "yyyy-MM-dd");
            date1 = DateUtils.parseDate(springTime, "yyyy-MM-dd");
            date2 = DateUtils.parseDate(autumnTime, "yyyy-MM-dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date.after(date1) && date.before(date2)) {
            item = "上";
        } else {
            item = "下";
        }
        Calendar cal = Calendar.getInstance();
        int yearD = cal.get(Calendar.YEAR);
        vo.setGradeName(NumberUtils.int2chineseNum(yearD - year + 1) + "年级" + item);
        vo.setClassStatus(classAnd.getStatus());

        //创建班级群
        GroupChat groupChat = new GroupChat();
        groupChat.setClassId(classAnd.getId());
        groupChat.setName(classAnd.getSchoolYear() + "级" + classAnd.getName() + "群");
        groupChat.setGroupType(1);
        groupChat.setGroupNum(this.getNineRandom());
        groupChat.setCreateBy(userId.toString());
        groupChat.setCreateTime(new Date());
        groupChat.setIsDeleted(false);
        groupChatDao.insertTemplate(groupChat, true);
        GroupMembers groupMembers1 = new GroupMembers();
        groupMembers1.setNickName(user.getName());
        groupMembers1.setUserId(userId);
        groupMembers1.setGroupChatId(groupChat.getId());
        groupMembers1.setCreateTime(new Date());
        groupMembers1.setCreateBy(userId.toString());
        groupMembers1.setType(2);
        groupMembers1.setIsDeleted(false);
        groupMembersDao.insertTemplate(groupMembers1);
        Boolean creategroup = tencentUtil.creategroup(groupChat);
        if (!creategroup) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return GlobalReponse.fail("创建失败");
        }
        UserFriendAndBlacklist groupMy = new UserFriendAndBlacklist();
        groupMy.setUserId(user.getId());
        groupMy.setRelevanceId(groupChat.getId());
        groupMy.setCreateTime(new Date());
        groupMy.setCreateBy(user.getId().toString());
        groupMy.setType(1);
        groupMy.setIsDeleted(false);
        userFriendAndBlacklistDao.insertTemplate(groupMy);

        return GlobalReponse.success("创建班级成功").setData(vo);
    }

    /**
     * 接收前端传递的腾讯群Id
     *
     * @param tencentId
     * @param classId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse tencentGroupId(String tencentId, Long classId, Long userId) {
        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, classId).andEq(GroupChat::getIsDeleted, false).single();
        groupChat.setUpdateTime(new Date());
        groupChat.setUpdateBy(userId.toString());
        groupChat.setTencentId(tencentId);
        groupChatDao.updateTemplateById(groupChat);
        return GlobalReponse.success("保存成功");
    }

    /**
     * 生成6位随机数递归
     *
     * @return
     */
    public String getSixRandom() {
        String sixRandom = UUIDUtil.sixRandom();
        ClassAnd classAnd = classAndDao.createLambdaQuery().andEq(ClassAnd::getClassNum, sixRandom).andEq(ClassAnd::getIsDeleted, false).single();
        if (classAnd == null) {
            return sixRandom;
        }
        return getSixRandom();
    }

    /**
     * 生成9位随机数递归
     *
     * @return
     */
    public String getNineRandom() {
        String nineRandom = UUIDUtil.nineRandom();
        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getGroupNum, nineRandom).andEq(GroupChat::getIsDeleted, false).single();
        if (groupChat == null) {
            return nineRandom;
        }
        return getNineRandom();
    }

    /**
     * 查询教师的班级列表
     *
     * @param
     * @return
     */
    @Override
    public GlobalReponse<ClassAndVo> getTeacherClassAnd(Long userId, Integer type) {
        User user = userDao.unique(userId);
        List<Integer> list = Arrays.asList(2, 3);
        List<ClassMembers> template = classMembersDao.createLambdaQuery().andEq(ClassMembers::getUserId, userId).andEq(ClassMembers::getIsDeleted, false).andIn(ClassMembers::getType, list).select();
        ArrayList<ClassAndVo> vos = new ArrayList<>();
        if (!template.isEmpty()) {
            for (ClassMembers members : template) {
                //班级信息
                ClassAnd classAnd = classAndDao.unique(members.getClassId());
                if (classAnd.getIsDeleted() == false) {
                    ClassAndVo vo = new ClassAndVo();
                    School school = schoolDao.unique(classAnd.getSchoolId());
                    vo.setCreateId(user.getId());
                    vo.setCreateName(user.getName());
                    vo.setCreateImage(user.getHeadImage());
                    vo.setSchoolId(school.getId());
                    vo.setProvince(school.getProvince());
                    vo.setCity(school.getCity());
                    vo.setCounty(school.getCounty());
                    vo.setSchoolName(school.getName());
                    vo.setClassId(classAnd.getId());
                    vo.setClassName(classAnd.getName());
                    vo.setClassNum(classAnd.getClassNum());
                    vo.setSchoolYear(classAnd.getSchoolYear() + "级");
                    long count = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classAnd.getId()).andEq(ClassMembers::getIsDeleted, false).count();
                    vo.setMemberNum(count);

                    GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, classAnd.getId()).andEq(GroupChat::getIsDeleted, false).single();
                    if (groupChat.getTencentId() != null) {
                        vo.setTencentId(groupChat.getTencentId());
                    }

                    //获取学年配置
                    ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
                    int year = Integer.valueOf(classAnd.getSchoolYear());
                    //判断学制
                    int num = classParam.getEducationSystem() == 1 ? 5 : 6;
                    //判断上下学期
                    String now = new SimpleDateFormat("MM-dd").format(new Date());
                    String spring = classParam.getSpringTime();
                    String autumn = classParam.getAutumnTime();
                    int newYear = year + 1;
                    String nowTime = year + "-" + now;
                    String springTime = year + "-" + spring;
                    String autumnTime = newYear + "-" + autumn;
                    Date date = null;
                    Date date1 = null;
                    Date date2 = null;
                    String item = null;
                    try {
                        date = DateUtils.parseDate(nowTime, "yyyy-MM-dd");
                        date1 = DateUtils.parseDate(springTime, "yyyy-MM-dd");
                        date2 = DateUtils.parseDate(autumnTime, "yyyy-MM-dd");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (date.after(date1) && date.before(date2)) {
                        item = "上";
                    } else {
                        item = "下";
                    }
                    Calendar cal = Calendar.getInstance();
                    int yearD = cal.get(Calendar.YEAR);
                    vo.setGradeName(NumberUtils.int2chineseNum(yearD - year + 1) + "年级" + item);

                    vo.setClassStatus(classAnd.getStatus());

                    //班级通知信息
                    ClassInform classInform = classInformDao.createLambdaQuery().andEq(ClassInform::getClassId, classAnd.getId()).andEq(ClassInform::getIsDeleted, false).desc(ClassInform::getCreateTime).single();
                    if (classInform != null) {
                        Inform inform = informDao.unique(classInform.getInformId());
                        vo.setLastNotice(inform);
                        ClassInformMember single = classInformMemberDao.createLambdaQuery().andEq(ClassInformMember::getClassId, classInform.getClassId()).andEq(ClassInformMember::getInformId, classInform.getInformId()).andEq(ClassInformMember::getUserId, userId).andEq(ClassInformMember::getIsDeleted, false).single();
                        if (single != null) {
                            if (single.getIsRead().equals(0)) {
                                vo.setInformIsRead(0);
                            } else {
                                vo.setInformIsRead(1);
                            }
                        } else {
                            vo.setInformIsRead(0);
                        }
                    }
                    //讲一讲
                    List<Video> newVideo = videoDao.getNewVideo(classAnd.getId());
                    ArrayList<VideoVo> videoVos = new ArrayList<>();
                    if (!newVideo.isEmpty()) {
                        for (Video video : newVideo) {
                            ClassVideoMember single = classVideoMemberDao.createLambdaQuery().andEq(ClassVideoMember::getClassId, classAnd.getId()).andEq(ClassVideoMember::getUserId, userId).andEq(ClassVideoMember::getVideoId, video.getId()).andEq(ClassVideoMember::getIsDeleted, false).single();
                            if (single != null) {
                                if (single.getIsRead().equals(0)) {
                                    VideoVo videoVo = VideoVoMapper.MAPPER.toVo(video);
                                    BigDecimal score = videoService.getVideoScore(videoVo.getId());
                                    videoVo.setScore(score);
                                    videoVos.add(videoVo);
                                }
                            } else {
                                VideoVo videoVo = VideoVoMapper.MAPPER.toVo(video);
                                BigDecimal score = videoService.getVideoScore(videoVo.getId());
                                videoVo.setScore(score);
                                videoVos.add(videoVo);
                            }
                        }
                        vo.setStudentVideo(videoVos);
                    }
                    //班级作业信息
                    ArrayList<JobDto> jobDtos = new ArrayList<>();
                    List<ClassJob> classJobs = classJobDao.createLambdaQuery().andEq(ClassJob::getClassId, classAnd.getId()).andEq(ClassJob::getIsDeleted, false).select();
                    List<Long> collect = classJobs.stream().map(ClassJob::getJobId).collect(Collectors.toList());
                    if (!collect.isEmpty()) {
                        List<Job> jobs = jobDao.createLambdaQuery().andIn(Job::getId, collect).andEq(Job::getIsDeleted, false).andGreat(Job::getDeadline, new Date()).desc(Job::getCreateTime).limit(1, 3).select();
                        for (Job job : jobs) {
                            JobDto jobDto = new JobDto();
                            jobDto.setJobId(job.getId());
                            jobDto.setJobName(job.getName());
                            Subject subject = subjectDao.unique(job.getSubjectId());
                            jobDto.setSubjectName(subject.getName());
                            jobDto.setDeadline(job.getDeadline());
                            jobDto.setDeadlineTime(job.getDeadline().getTime());
                            if (new Date().getTime() > job.getDeadline().getTime()) {
                                jobDto.setIsDeadline(true);
                            } else {
                                jobDto.setIsDeadline(false);
                            }
                            //学生数量
                            long studentCount = classMembersDao.createLambdaQuery().andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).andEq(ClassMembers::getClassId, classAnd.getId()).count();

                            jobDto.setStudentNum(studentCount);

                            jobDtos.add(jobDto);

                            //题目总数
                            List<JobQuestion> questions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, job.getId()).andEq(JobQuestion::getIsDeleted, false).select();
                            jobDto.setTopicNum(Long.valueOf(questions.size()));

                            //学生的作业
                            List<UserJob> userJobs = userJobDao.createLambdaQuery().andEq(UserJob::getClassId, classAnd.getId()).andEq(UserJob::getJobId, job.getId()).andEq(UserJob::getIsDeleted, false).select();
                            Long submitNum = 0L;
                            for (UserJob userJob : userJobs) {
                                if (userJob.getStatus() != 0) {
                                    submitNum += 1;
                                }
                            }
                            jobDto.setSubmit(submitNum);
                        }
                        vo.setClassJobDto(jobDtos);
                    }
                    if (type != null && type == 1) {
                        if (vo.getClassStatus().equals(0)) {
                            vos.add(vo);
                        }
                    } else {
                        vos.add(vo);
                    }
                }
            }
        }

        return GlobalReponse.success(vos);
    }

    /**
     * 根据班级id查询班级详情信息
     *
     * @param classId
     * @return
     */
    @Override
    public GlobalReponse<ClassAndVo> getClassById(Long classId, Long userId) {
        //班级信息
        ClassAnd classAnd = classAndDao.unique(classId);
        ClassAndVo vo = new ClassAndVo();
        School school = schoolDao.unique(classAnd.getSchoolId());
        User user = userDao.unique(Long.valueOf(classAnd.getCreateBy()));
        ClassMembers single1 = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getUserId, userId).andEq(ClassMembers::getIsDeleted, false).single();
        vo.setMyNickname(single1.getNickname());
        vo.setCreateId(user.getId());
        vo.setCreateName(user.getName());
        vo.setCreateImage(user.getHeadImage());
        vo.setSchoolId(school.getId());
        vo.setProvince(school.getProvince());
        vo.setCity(school.getCity());
        vo.setCounty(school.getCounty());
        vo.setSchoolName(school.getName());
        vo.setClassId(classAnd.getId());
        vo.setClassName(classAnd.getName());
        vo.setClassNum(classAnd.getClassNum());
        vo.setSchoolYear(classAnd.getSchoolYear());
        vo.setClassStatus(classAnd.getStatus());

        //获取学年配置
        ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
        int year = Integer.valueOf(classAnd.getSchoolYear());
        //判断学制
        int num = classParam.getEducationSystem() == 1 ? 5 : 6;
        //判断上下学期
        String now = new SimpleDateFormat("MM-dd").format(new Date());
        String spring = classParam.getSpringTime();
        String autumn = classParam.getAutumnTime();
        int newYear = year + 1;
        String nowTime = year + "-" + now;
        String springTime = year + "-" + spring;
        String autumnTime = newYear + "-" + autumn;

//        Date nowTime = null;
//        Date springTime = null;
//        Date autumnTime = null;
//        try {
//            nowTime = DateUtils.parseDate(now, "MM-dd");
//            springTime = DateUtils.parseDate(spring, "MM-dd");
//            autumnTime = DateUtils.parseDate(autumn, "MM-dd");
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        Date date = null;
        Date date1 = null;
        Date date2 = null;
        String item = null;
        try {
            date = DateUtils.parseDate(nowTime, "yyyy-MM-dd");
            date1 = DateUtils.parseDate(springTime, "yyyy-MM-dd");
            date2 = DateUtils.parseDate(autumnTime, "yyyy-MM-dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date.after(date1) && date.before(date2)) {
            item = "上";
        } else {
            item = "下";
        }
        Calendar cal = Calendar.getInstance();
        int yearD = cal.get(Calendar.YEAR);
        vo.setGradeName(NumberUtils.int2chineseNum(yearD - year + 1) + "年级" + item);
        long count = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classAnd.getId()).andEq(ClassMembers::getIsDeleted, false).count();
        vo.setMemberNum(count);

        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, classAnd.getId()).andEq(GroupChat::getIsDeleted, false).single();
        if (groupChat.getTencentId() != null) {
            vo.setTencentId(groupChat.getTencentId());
        }

        //班级通知信息
        ClassInform classInform = classInformDao.createLambdaQuery().andEq(ClassInform::getClassId, classId).andEq(ClassInform::getIsDeleted, false).desc(ClassInform::getCreateTime).single();
        if (classInform != null) {
            Inform single = informDao.createLambdaQuery().andEq(Inform::getId, classInform.getInformId()).andEq(Inform::getIsDeleted, false).andEq(Inform::getStatus, 1).single();
            vo.setLastNotice(single);
        }

        //讲一讲
        List<Video> newVideo = videoDao.getNewVideo(classAnd.getId());
        if (!newVideo.isEmpty()) {
            List<VideoVo> listVo = VideoVoMapper.MAPPER.toVo(newVideo);
            for (VideoVo videoVo : listVo) {
                BigDecimal score = videoService.getVideoScore(videoVo.getId());
                videoVo.setScore(score);
            }
            if (listVo.size() > 10) {
                List<VideoVo> videoVos = listVo.subList(0, 10);
                vo.setStudentVideo(videoVos);
            } else {
                vo.setStudentVideo(listVo);
            }
        }

        //班级作业信息
        ArrayList<JobDto> jobDtos = new ArrayList<>();
        List<ClassJob> classJobs = classJobDao.createLambdaQuery().andEq(ClassJob::getClassId, classId).andEq(ClassJob::getIsDeleted, false).select();
        List<Long> collect = classJobs.stream().map(ClassJob::getJobId).collect(Collectors.toList());
        if (collect.size() > 0) {
            List<Job> jobs = jobDao.createLambdaQuery().andIn(Job::getId, collect).andEq(Job::getIsDeleted, false).desc(Job::getCreateTime).limit(1, 10).select();
            for (Job job : jobs) {
                JobDto jobDto = new JobDto();
                jobDto.setJobId(job.getId());
                jobDto.setJobName(job.getName());
                jobDto.setDeadline(job.getDeadline());
                jobDto.setDeadlineTime(job.getDeadline().getTime());
                Subject subject = subjectDao.unique(job.getSubjectId());
                jobDto.setSubjectName(subject.getName());
                //是否过截止时间
                if (new Date().getTime() > job.getDeadline().getTime()) {
                    jobDto.setIsDeadline(true);
                } else {
                    jobDto.setIsDeadline(false);
                }
                if (job.getCreateBy().equals(userId.toString())) {
                    jobDto.setIsMy(true);
                    List<JobQuestion> questions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, job.getId()).andEq(JobQuestion::getIsDeleted, false).select();
                    List<Long> ids = questions.stream().map(JobQuestion::getQuestionId).collect(Collectors.toList());
                    List<Question> select = questionDao.createLambdaQuery().andIn(Question::getId, ids).andEq(Question::getIsDeleted, false).andEq(Question::getType, 1).select();
                    if (!select.isEmpty()) {
                        List<Long> zIds = select.stream().map(Question::getId).collect(Collectors.toList());
                        List<QuestionRecord> questionRecords = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getJobId, job.getId()).andIn(QuestionRecord::getQuestionId, zIds).andEq(QuestionRecord::getIsCheck, false).andEq(QuestionRecord::getIsDeleted, false).select();
                        if (!questionRecords.isEmpty()) {
                            jobDto.setIsCheck(true);
                        } else {
                            jobDto.setIsCheck(false);
                        }
                    }
                } else {
                    jobDto.setIsMy(false);
                }
                User unique = userDao.unique(job.getCreateBy());
                jobDto.setPusherId(unique.getId());
                jobDto.setPusherName(unique.getName());
                jobDto.setPusherImage(unique.getHeadImage());

                //题目总数
                List<JobQuestion> questions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, job.getId()).andEq(JobQuestion::getIsDeleted, false).select();
                jobDto.setTopicNum(Long.valueOf(questions.size()));

                //学生数量
                long studentCount = classMembersDao.createLambdaQuery().andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).andEq(ClassMembers::getClassId, classId).count();

                jobDto.setStudentNum(studentCount);
                //学生的作业
                List<UserJob> userJobs = userJobDao.createLambdaQuery().andEq(UserJob::getClassId, classId).andEq(UserJob::getJobId, job.getId()).andEq(UserJob::getIsDeleted, false).select();

                //学生得分
                BigDecimal studentScore = new BigDecimal(0);
                Long correctNum = 0L;
                Long noCorrectNum = 0L;
                Long submitNum = 0L;
                Long noSubmitNum = 0L;
                for (UserJob userJob : userJobs) {
                    if (userJob.getScore() != null) {
                        studentScore = studentScore.add(userJob.getScore());
                    }
                    if (userJob.getStatus() != 0) {
                        submitNum += 1;
                        if (userJob.getScore() != null && userJob.getScore().compareTo(job.getScore()) == 0) {
                            correctNum += 1;
                        } else {
                            noCorrectNum += 1;
                        }
                    } else {
                        noSubmitNum += 1;
                    }
                    List<QuestionRecord> questionRecords = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getUserId, userJob.getUserId()).andEq(QuestionRecord::getJobId, userJob.getJobId()).select();
                    for (QuestionRecord questionRecord : questionRecords) {
                        if (questionRecord != null && questionRecord.getCorrect() != null && questionRecord.getCorrect() == null) {
                            jobDto.setStatus(1);
                        }
                    }
                }
                jobDto.setSubmit(submitNum);
                jobDto.setNoSubmit(noSubmitNum);
                jobDto.setCorrectNum(correctNum);
                jobDto.setNoCorrectNum(noCorrectNum);

                //平均正确率
                if (!studentScore.equals(BigDecimal.ZERO) && studentCount != 0) {
                    jobDto.setAccuracy(studentScore.divide(job.getScore().multiply(new BigDecimal(studentCount)), 0).multiply(new BigDecimal(100)).toString());
                } else {
                    jobDto.setAccuracy("0");
                }
                jobDtos.add(jobDto);
            }
            vo.setClassJobDto(jobDtos);
        }

        //查询教师人数和列表
        Long teacherNum = classAndService.countTeacher(classId);
        List<ClassMembers> teacher = classAndService.teacherList(classId);
        vo.setTeacherList(teacher);
        vo.setTeacherNum(teacherNum);
        //查询学生数量和列表
        Long studentNum = classAndService.countStudent(classAnd.getId());
        List<ClassMembers> student = classAndService.studentList(classAnd.getId());
        vo.setStudentNum(studentNum);
        vo.setStudentList(student);
        return GlobalReponse.success(vo);
    }

    /**
     * 修改班级内的昵称
     *
     * @param nickname
     * @param classId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse changeNickname(String nickname, Long classId, Long userId) {
        ClassMembers classMembers = classAndService.findClassMember(userId, classId);
        classMembers.setNickname(nickname);
        classMembers.setUpdateBy(userId.toString());
        classMembers.setUpdateTime(new Date());
        classMembersDao.updateTemplateById(classMembers);
        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, classId).andEq(GroupChat::getIsDeleted, false).single();
        if (groupChat != null) {
            GroupMembers groupMembers = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getUserId, userId).andEq(GroupMembers::getGroupChatId, groupChat.getId()).andEq(GroupMembers::getIsDeleted, false).single();
            groupMembers.setNickName(nickname);
            groupMembers.setUpdateBy(userId.toString());
            groupMembers.setUpdateTime(new Date());
            groupMembersDao.updateTemplateById(groupMembers);
            Boolean flag = tencentUtil.modifyGroupMemberInfo(groupMembers);
            if (!flag) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return GlobalReponse.fail("修改失败");
            }
        }
        return GlobalReponse.success("修改成功");
    }

    /**
     * 解散班级
     *
     * @param classId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse dissolveClass(Long classId, Long userId) {
        List<ClassMembers> classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).select();
        if (!classMembers.isEmpty()) {
            return GlobalReponse.fail("请移除全部学生后再解散班级");
        }
        ClassAnd classAnd = classAndDao.unique(classId);
        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, classId).andEq(GroupChat::getIsDeleted, false).single();
        Boolean flag = tencentUtil.destroyGroup(groupChat.getId());
        if (flag) {
            classAnd.setIsDeleted(true);
            classAnd.setUpdateBy(userId.toString());
            classAnd.setUpdateTime(new Date());
            classAndDao.updateById(classAnd);
            groupChat.setIsDeleted(true);
            groupChat.setUpdateTime(new Date());
            groupChat.setUpdateBy(userId.toString());
            groupChatDao.updateTemplateById(groupChat);
            List<GroupMembers> groupMembers = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupChat.getId()).andEq(GroupMembers::getIsDeleted, false).select();
            for (GroupMembers groupMember : groupMembers) {
                groupMember.setIsDeleted(true);
                groupMember.setUpdateBy(userId.toString());
                groupMember.setUpdateTime(new Date());
                groupMembersDao.updateTemplateById(groupMember);
            }
            return GlobalReponse.success("操作成功");
        }
        return GlobalReponse.fail("操作失败");
    }

    /**
     * 根据班级Id查看班级通知
     *
     * @param pageQuery
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<InformDto>> getClassInformById(Long userId, PageQuery<Inform> pageQuery, Long classId) {
        informDao.getClassInformById(pageQuery);
        List<Inform> list = pageQuery.getList();
        ArrayList<InformDto> dtos = new ArrayList<>();
        for (Inform inform : list) {
            ClassInformMember single = classInformMemberDao.createLambdaQuery().andEq(ClassInformMember::getClassId, classId).andEq(ClassInformMember::getInformId, inform.getId()).andEq(ClassInformMember::getUserId, userId).andEq(ClassInformMember::getIsDeleted, 0).single();
            if (single != null) {
                single.setIsRead(1);
                classInformMemberDao.updateTemplateById(single);
            } else {
                ClassInformMember informMember = new ClassInformMember();
                informMember.setClassId(classId);
                informMember.setInformId(inform.getId());
                informMember.setUserId(userId);
                informMember.setIsDeleted(false);
                informMember.setIsRead(1);
                informMember.setCreateTime(new Date());
                informMember.setCreateBy(userId.toString());
                classInformMemberDao.insertTemplate(informMember);
            }
            InformDto dto = new InformDto();
            dto.setId(inform.getId());
            dto.setContent(inform.getContent());
            dto.setImages(inform.getImages());
            dto.setCreateTime(inform.getCreateTime());
            ClassMembers classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getUserId, inform.getCreateBy()).single();
            dto.setCreateNickname(classMembers.getNickname());
            User user = userDao.unique(inform.getCreateBy());
            dto.setCreateId(user.getId());
            dto.setCreateImage(user.getHeadImage());
            dto.setCreateStatus(user.getIsLocked());
            if (user.getId().equals(userId)) {
                dto.setIsMy(true);
            } else {
                dto.setIsMy(false);
            }
            dto.setStatus(inform.getStatus());
            dtos.add(dto);
        }
        PageQuery<InformDto> query = new PageQuery<>();
        query.setList(dtos);
        query.setTotalRow(pageQuery.getTotalRow());
        query.setPageNumber(pageQuery.getPageNumber());
        query.setPageSize(pageQuery.getPageSize());
        return GlobalReponse.success(query);
    }

    /**
     * 查看我的通知
     *
     * @param userId
     * @param pageQuery
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<Inform>> getMyInform(Long userId, PageQuery<Inform> pageQuery) {
        informDao.getMyInform(pageQuery);
        List<Inform> list = pageQuery.getList();
        for (Inform inform : list) {
            List<ClassInform> informs = classInformDao.createLambdaQuery().andEq(ClassInform::getInformId, inform.getId()).andEq(ClassInform::getIsDeleted, false).select();
            List<Long> collect = informs.stream().map(ClassInform::getClassId).collect(Collectors.toList());
            List<ClassAnd> classAnds = classAndDao.createLambdaQuery().andIn(ClassAnd::getId, collect).andEq(ClassAnd::getIsDeleted, false).select();
            ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
            ArrayList<String> arrayList = new ArrayList<>();
            for (ClassAnd classAnd : classAnds) {
                String className = classAnd.getSchoolYear() + "级" + classAnd.getName();
                arrayList.add(className);
            }
            inform.set("classNames", arrayList);

        }
        pageQuery.setList(list);
        return GlobalReponse.success(pageQuery);
    }

    /**
     * 删除我发布的通知
     *
     * @param userId
     * @param informId
     * @return
     */
    @Override
    public GlobalReponse deleteMyInform(Long userId, Long informId) {
        Inform inform = new Inform();
        inform.setCreateBy(userId.toString());
        inform.setIsDeleted(false);
        inform.setId(informId);
        Inform one = informDao.templateOne(inform);
        if (one != null) {
            one.setIsDeleted(true);
            one.setUpdateBy(userId.toString());
            one.setUpdateTime(new Date());
            informDao.updateById(one);
        }
        List<ClassInform> classInforms = classInformDao.createLambdaQuery().andEq(ClassInform::getInformId, informId).andEq(ClassInform::getIsDeleted, false).select();
        for (ClassInform classInform : classInforms) {
            classInform.setIsDeleted(true);
            classInform.setUpdateBy(userId.toString());
            classInform.setUpdateTime(new Date());
            classInformDao.updateById(classInform);
        }
        return GlobalReponse.success("删除成功");
    }

    /**
     * 发布通知
     *
     * @param userId
     * @param informPushDto
     * @return
     */
    @Override
    public GlobalReponse pushInform(Long userId, InformPushDto informPushDto) {
        if (informPushDto.getImages() != null && !informPushDto.getImages().equals("")) {
            for (String img : informPushDto.getImages().split(",")) {
                Boolean flag = aLiYunUtils.aliyunImageSyncCheck(img);
                if (!flag) {
                    return GlobalReponse.fail("图片存在违规信息，请更换图片后重新上传");
                }
            }
        }
        Integer check = CommentUtil.checkComment(informPushDto.getContent());
        if (check == 2 || check == 1) {
            Inform inform = new Inform();
            inform.setContent(informPushDto.getContent());
            inform.setImages(informPushDto.getImages());
            inform.setCreateBy(userId.toString());
            inform.setCreateTime(new Date());
            inform.setIsDeleted(false);
            inform.setStatus(1);
            informDao.insert(inform, true);
            for (Long classId : informPushDto.getClassIds()) {
                ClassInformMember single = classInformMemberDao.createLambdaQuery().andEq(ClassInformMember::getClassId, classId).andEq(ClassInformMember::getInformId, inform.getId()).andEq(ClassInformMember::getUserId, userId).andEq(ClassInformMember::getIsDeleted, 0).single();
                if (single != null) {
                    single.setIsRead(1);
                    classInformMemberDao.updateTemplateById(single);
                } else {
                    ClassInformMember informMember = new ClassInformMember();
                    informMember.setClassId(classId);
                    informMember.setInformId(inform.getId());
                    informMember.setUserId(userId);
                    informMember.setIsDeleted(false);
                    informMember.setIsRead(1);
                    informMember.setCreateTime(new Date());
                    informMember.setCreateBy(userId.toString());
                    classInformMemberDao.insertTemplate(informMember);
                }
                ClassInform classInform = new ClassInform();
                classInform.setClassId(classId);
                classInform.setInformId(inform.getId());
                classInform.setIsDeleted(false);
                classInform.setCreateBy(userId.toString());
                classInform.setCreateTime(new Date());
                classInformDao.insert(classInform);
            }
            return GlobalReponse.success("发布成功");
        } else if (check == 0) {
            return GlobalReponse.fail("通知含有敏感词，禁止发布");
        }
        return GlobalReponse.fail("发布失败");
    }

    /**
     * 获取我的好友列表
     *
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<FriendDto> getFriendList(Long userId, Long classId, String keyword) {
//        UserFriendAndBlacklist andBlacklist = new UserFriendAndBlacklist();
//        andBlacklist.setUserId(userId);
//        andBlacklist.setType(0);
//        andBlacklist.setIsDeleted(false);
        // List<UserFriendAndBlacklist> friendList = userFriendAndBlacklistDao.template(andBlacklist);
        if (keyword != null && keyword.equals("")) {
            keyword = null;
        }
        List<UserFriendAndBlacklist> friendList = userFriendAndBlacklistDao.getFriendList(userId, keyword);
        if (!friendList.isEmpty()) {
            ArrayList<FriendDto> dtos = new ArrayList<>();
            for (UserFriendAndBlacklist friend : friendList) {
                FriendDto dto = new FriendDto();
                User user = userDao.unique(friend.getRelevanceId());
                dto.setId(user.getId());
                dto.setImage(user.getHeadImage());
                dto.setNickname(user.getName());
                ClassMembers classMembers = new ClassMembers();
                classMembers.setUserId(user.getId());
                classMembers.setClassId(classId);
                classMembers.setIsDeleted(false);
                ClassMembers templateOne = classMembersDao.templateOne(classMembers);
                if (templateOne != null) {
                    dto.setExists(true);
                } else {
                    dto.setExists(false);
                }
                dtos.add(dto);
            }
            Map<String, List<FriendDto>> res = dtos.stream()
                    .collect(Collectors.groupingBy(o ->
                                    chineseInital.getFirstLetter(o.getNickname()).toUpperCase()
                            , TreeMap::new, Collectors.toList()));
            ArrayList maps = new ArrayList<>();

            for (Map.Entry<String, List<FriendDto>> entry : res.entrySet()) {
                Map map = new IdentityHashMap<>();
                map.put("letter", entry.getKey());
                map.put("list", entry.getValue());
                maps.add(map);
            }
            return GlobalReponse.success(maps);
        }
        return GlobalReponse.fail("暂无好友");
    }

    /**
     * 邀请好友加入班级
     *
     * @param dto
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<ClassAndVo> addClassMembers(AddDeleteClassMembersDto dto, Long userId) {
        ClassAnd classAnd = classAndDao.unique(dto.getClassId());
        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, dto.getClassId()).andEq(GroupChat::getIsDeleted, false).single();
        for (Long id : dto.getIds()) {
            List<CreateGroupReturn> returns = tencentUtil.addGroupMember(groupChat.getId(), id.toString(), 0);
            for (CreateGroupReturn aReturn : returns) {
                if (aReturn.getResult().equals("1")) {
                    User user = userDao.unique(id);
                    ClassMembers classMembers = new ClassMembers();
                    classMembers.setClassId(dto.getClassId());
                    classMembers.setUserId(Long.valueOf(id.toString()));
                    classMembers.setIsDeleted(false);
                    classMembers.setCreateBy(userId.toString());
                    classMembers.setNickname(user.getName());
                    classMembers.setType(user.getUserType());
                    classMembers.setHeadImage(user.getHeadImage());
                    classMembersDao.insertTemplate(classMembers);
                    GroupMembers groupMembers = new GroupMembers();
                    groupMembers.setUserId(user.getId());
                    groupMembers.setNickName(user.getName());
                    groupMembers.setGroupChatId(groupChat.getId());
                    groupMembers.setCreateBy(userId.toString());
                    groupMembers.setCreateTime(new Date());
                    if (user.getUserType() == 1) {
                        groupMembers.setType(0);
                    } else if (user.getUserType() == 2) {
                        Boolean flag = tencentUtil.setGroupMember(user.getId(), groupChat.getId(), 1);
                        if (flag) {
                            groupMembers.setType(1);
                        }else {
                            groupMembers.setType(0);
                        }
                    }
                    groupMembersDao.insertTemplate(groupMembers);
                    UserFriendAndBlacklist friendAndBlacklist = new UserFriendAndBlacklist();
                    friendAndBlacklist.setUserId(id);
                    friendAndBlacklist.setRelevanceId(groupChat.getId());
                    friendAndBlacklist.setType(1);
                    friendAndBlacklist.setIsDeleted(false);
                    friendAndBlacklist.setCreateBy(userId.toString());
                    friendAndBlacklist.setCreateTime(new Date());
                    userFriendAndBlacklistDao.insertTemplate(friendAndBlacklist);
                }
            }

        }
        ClassAndVo vo = new ClassAndVo();
        School school = schoolDao.unique(classAnd.getSchoolId());
        User user = userDao.unique(classAnd.getCreateBy());
        vo.setCreateId(user.getId());
        vo.setCreateName(user.getName());
        vo.setCreateImage(user.getHeadImage());
        vo.setSchoolId(school.getId());
        vo.setProvince(school.getProvince());
        vo.setCity(school.getCity());
        vo.setCounty(school.getCounty());
        vo.setSchoolName(school.getName());
        vo.setClassId(classAnd.getId());
        vo.setClassName(classAnd.getName());
        vo.setClassNum(classAnd.getClassNum());
        vo.setSchoolYear(classAnd.getSchoolYear() + "级");
        long count = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classAnd.getId()).andEq(ClassMembers::getIsDeleted, false).count();
        vo.setMemberNum(count);
        if (groupChat.getTencentId() != null) {
            vo.setTencentId(groupChat.getTencentId());
        }

        //获取学年配置
        ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
        int year = Integer.valueOf(classAnd.getSchoolYear());
        //判断学制
        int num = classParam.getEducationSystem() == 1 ? 5 : 6;
        //判断上下学期
        String now = new SimpleDateFormat("MM-dd").format(new Date());
        String spring = classParam.getSpringTime();
        String autumn = classParam.getAutumnTime();
        int newYear = year + 1;
        String nowTime = year + "-" + now;
        String springTime = year + "-" + spring;
        String autumnTime = newYear + "-" + autumn;

//        Date nowTime = null;
//        Date springTime = null;
//        Date autumnTime = null;
//        try {
//            nowTime = DateUtils.parseDate(now, "MM-dd");
//            springTime = DateUtils.parseDate(spring, "MM-dd");
//            autumnTime = DateUtils.parseDate(autumn, "MM-dd");
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        Date date = null;
        Date date1 = null;
        Date date2 = null;
        String item = null;
        try {
            date = DateUtils.parseDate(nowTime, "yyyy-MM-dd");
            date1 = DateUtils.parseDate(springTime, "yyyy-MM-dd");
            date2 = DateUtils.parseDate(autumnTime, "yyyy-MM-dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date.after(date1) && date.before(date2)) {
            item = "上";
        } else {
            item = "下";
        }
        Calendar cal = Calendar.getInstance();
        int yearD = cal.get(Calendar.YEAR);
        vo.setGradeName(NumberUtils.int2chineseNum(yearD - year + 1) + "年级" + item);
        vo.setClassStatus(classAnd.getStatus());
        return GlobalReponse.success("邀请成功").setData(vo);
    }

    /**
     * 删除班级成员
     *
     * @param dto
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse deletedClassMembers(AddDeleteClassMembersDto dto, Long userId) {
        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, dto.getClassId()).andEq(GroupChat::getIsDeleted, false).single();
        for (Long id : dto.getIds()) {
            Boolean flag = tencentUtil.deleteGroupMember(groupChat.getId(), id.toString());
            if (flag) {
                ClassMembers classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, dto.getClassId()).andEq(ClassMembers::getUserId, id).andEq(ClassMembers::getIsDeleted, false).single();
                classMembers.setIsDeleted(true);
                classMembers.setUpdateBy(userId.toString());
                classMembers.setUpdateTime(new Date());
                classMembersDao.updateTemplateById(classMembers);
                GroupMembers groupMembers = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupChat.getId()).andEq(GroupMembers::getUserId, id).andEq(GroupMembers::getIsDeleted, false).single();
                groupMembers.setIsDeleted(true);
                groupMembers.setUpdateBy(userId.toString());
                groupMembers.setUpdateTime(new Date());
                groupMembersDao.updateTemplateById(groupMembers);
                UserFriendAndBlacklist andBlacklist = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getRelevanceId, groupChat.getId()).andEq(UserFriendAndBlacklist::getUserId, id).andEq(UserFriendAndBlacklist::getType, 1).andEq(UserFriendAndBlacklist::getIsDeleted, false).single();
                andBlacklist.setIsDeleted(true);
                andBlacklist.setUpdateBy(userId.toString());
                andBlacklist.setUpdateTime(new Date());
                userFriendAndBlacklistDao.updateTemplateById(andBlacklist);
                KickOut kickOut = new KickOut();
                kickOut.setUserId(id);
                kickOut.setRelevanceId(dto.getClassId());
                kickOut.setType(2);
                kickOut.setIsRead(0);
                kickOut.setIsDeleted(false);
                kickOut.setCreateTime(new Date());
                kickOut.setCreateBy(userId.toString());
                kickOutDao.insertTemplate(kickOut);
                return GlobalReponse.success("删除成功");
            }
        }
        return GlobalReponse.fail("删除失败");
    }

    /**
     * 获取全部学科
     *
     * @return
     */
    @Override
    public GlobalReponse<Subject> getSubject() {
        Subject subject = new Subject();
        subject.setIsDeleted(false);
        List<Subject> subjects = subjectDao.template(subject);
        return GlobalReponse.success(subjects);
    }

    /**
     * 获取全部年级
     *
     * @return
     */
    @Override
    public GlobalReponse<Grade> getGrade() {
        Grade grade = new Grade();
        grade.setIsDeleted(false);
        List<Grade> grades = gradeDao.template(grade);
        return GlobalReponse.success(grades);
    }

    /**
     * 获取老师发布过的作业学科
     *
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<Subject> getUserJobGrade(Long userId) {
        List<Question> questions = questionDao.createLambdaQuery().andEq(Question::getWarehouseType, 1).andEq(Question::getCreateBy, userId).andEq(Question::getIsDeleted, false).select();
        List<Long> collect = questions.stream().map(Question::getSubjectId).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            List<Subject> subjects = subjectDao.createLambdaQuery().andEq(Subject::getIsDeleted, false).andIn(Subject::getId, collect).select();
            return GlobalReponse.success(subjects);
        }
        return GlobalReponse.success("暂无发布过的学科");
    }

    /**
     * 获取题库数量
     *
     * @param type
     * @param subjectId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<QuestionCountDto> getQuestionCount(Integer type, Long subjectId, Long gradeId, Long userId) {
        QuestionCountDto questionCountDto = new QuestionCountDto();
        Question question = new Question();

        if (type == 0) {
            //作业题库
            question.setWarehouseType(1);
            question.setCreateBy(userId.toString());
        }
        if (type == 1) {
            //淘学题库
            question.setWarehouseType(0);
            question.setCreateBy(null);
        }
        if (type == 2) {
            //共享题库
            question.setShareType(1);
            question.setCreateBy(null);
        }
        if (subjectId != 0) {
            question.setSubjectId(subjectId);
            //全部
            long all = questionDao.getQuestionCount(question, gradeId);
            questionCountDto.setAllNum(all);

            //单选
            question.setType(QuestionType.DANXUANTI);
            long dan = questionDao.getQuestionCount(question, gradeId);
            questionCountDto.setChoiceNum(dan);

            //主观
            question.setType(QuestionType.ZHUGUANTI);
            long zhu = questionDao.getQuestionCount(question, gradeId);
            questionCountDto.setSubjectiveNum(zhu);

            //线下
            question.setType(QuestionType.XIANXIATI);
            long xian = questionDao.getQuestionCount(question, gradeId);
            questionCountDto.setOfflineNum(xian);
        }
        if (subjectId == 0 && type != 0) {
            FavoritesQuestion favoritesQuestion = new FavoritesQuestion();
            favoritesQuestion.setIsDeleted(false);
            favoritesQuestion.setUserId(userId);
            if (type == 2) {
                favoritesQuestion.setBackType(2);
            }
            if (type == 1) {
                favoritesQuestion.setBackType(1);
            }
            List<FavoritesQuestion> template = favoritesQuestionDao.template(favoritesQuestion);
            List<Long> collect = template.stream().map(FavoritesQuestion::getQuestionId).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                if (gradeId == null || gradeId == 0) {
                    //全部
                    long all = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andIn(Question::getId, collect).count();
                    questionCountDto.setAllNum(all);

                    //单选
                    long dan = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andEq(Question::getType, QuestionType.DANXUANTI).andIn(Question::getId, collect).count();
                    questionCountDto.setChoiceNum(dan);

                    //主观
                    long zhu = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andEq(Question::getType, QuestionType.ZHUGUANTI).andIn(Question::getId, collect).count();
                    questionCountDto.setSubjectiveNum(zhu);

                    //线下
                    long xian = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andEq(Question::getType, QuestionType.XIANXIATI).andIn(Question::getId, collect).count();
                    questionCountDto.setOfflineNum(xian);
                } else {
                    List<Long> longs = questionDao.getGradeQuestion(gradeId);
                    //全部
                    long all = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andIn(Question::getId, collect).andIn(Question::getId, longs).count();
                    questionCountDto.setAllNum(all);

                    //单选
                    long dan = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andEq(Question::getType, QuestionType.DANXUANTI).andIn(Question::getId, collect).andEq(Question::getType, 0).andIn(Question::getId, longs).count();
                    questionCountDto.setChoiceNum(dan);

                    //主观
                    long zhu = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andEq(Question::getType, QuestionType.ZHUGUANTI).andIn(Question::getId, collect).andEq(Question::getType, 1).andIn(Question::getId, longs).count();
                    questionCountDto.setSubjectiveNum(zhu);

                    //线下
                    long xian = questionDao.createLambdaQuery().andEq(Question::getIsDeleted, false).andEq(Question::getType, QuestionType.XIANXIATI).andIn(Question::getId, collect).andEq(Question::getType, 2).andIn(Question::getId, longs).count();
                    questionCountDto.setOfflineNum(xian);
                }

            } else {
                questionCountDto.setAllNum(0L);
                questionCountDto.setChoiceNum(0L);
                questionCountDto.setSubjectiveNum(0L);
                questionCountDto.setOfflineNum(0L);
            }
        }
        if (subjectId == 0 && type == 0) {
            Question myQuestion = new Question();
            myQuestion.setWarehouseType(1);
            myQuestion.setCreateBy(userId.toString());
            //全部
            long all = questionDao.getQuestionCount(myQuestion, gradeId);
            questionCountDto.setAllNum(all);

            //单选
            myQuestion.setType(QuestionType.DANXUANTI);
            long dan = questionDao.getQuestionCount(myQuestion, gradeId);
            questionCountDto.setChoiceNum(dan);

            //主观
            myQuestion.setType(QuestionType.ZHUGUANTI);
            long zhu = questionDao.getQuestionCount(myQuestion, gradeId);
            questionCountDto.setSubjectiveNum(zhu);

            //线下
            myQuestion.setType(QuestionType.XIANXIATI);
            long xian = questionDao.getQuestionCount(myQuestion, gradeId);
            questionCountDto.setOfflineNum(xian);
        }
        return GlobalReponse.success(questionCountDto);
    }

    /**
     * 多条件查询题库
     *
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<GetQuestionPageVo>> getQuestionPage(QuestionPageDto dto, Long userId) {
        if (dto.getSubjectId() == null) {
            dto.setSubjectId(0L);
        }
        if (dto.getType() == 0) {//我的题库
            PageQuery<Question> pageQuery = new PageQuery<>();
            pageQuery.setPageNumber(dto.getPageNo());
            pageQuery.setPageSize(10);
            pageQuery.setPara("userId", userId);
            pageQuery.setPara("subjectId", dto.getSubjectId());
            pageQuery.setPara("gradeId", dto.getGradeId());
            pageQuery.setPara("status", dto.getStatus());
            pageQuery.setPara("title", dto.getTitle());
            pageQuery.setPara("keyword", dto.getKeyword());
            questionDao.getMyQuestionPage(pageQuery);
            List<GetQuestionPageVo> vos = new ArrayList<>();
            for (Question question : pageQuery.getList()) {
                GetQuestionPageVo vo = new GetQuestionPageVo();
                BeanUtils.copyProperties(question, vo);
                Question useQuestion = questionDao.getUseQuestion(userId, question.getId());
                if (useQuestion == null) {
                    vo.setIsUse(false);
                } else {
                    vo.setIsUse(true);
                }
                if (question.getPushStatus().equals(1)) {
                    User user = userDao.unique(question.getCreateBy());
                    vo.setCreateBy(user.getId().toString());
                    vo.setCreateName(user.getName());
                    vo.setCreateImage(user.getHeadImage());
                    vo.setCreateTime(question.getCreateTime());
                    vos.add(vo);
                }
            }
            PageQuery<GetQuestionPageVo> query = new PageQuery<>();
            query.setPageNumber(pageQuery.getPageNumber());
            query.setPageSize(pageQuery.getPageSize());
            query.setList(vos);
            query.setTotalRow(pageQuery.getTotalRow());
            return GlobalReponse.success(query);
        }
        if (dto.getType() == 1) {//淘学题库
            PageQuery<Question> pageQuery = new PageQuery<>();
            pageQuery.setPageNumber(dto.getPageNo());
            pageQuery.setPageSize(10);
            pageQuery.setPara("subjectId", dto.getSubjectId());
            pageQuery.setPara("gradeId", dto.getGradeId());
            pageQuery.setPara("status", dto.getStatus());
            pageQuery.setPara("title", dto.getTitle());
            if (dto.getSubjectId() != 0) {
                questionDao.getTaoxuePage(pageQuery);
                List<GetQuestionPageVo> vos = new ArrayList<>();
                for (Question question : pageQuery.getList()) {
                    GetQuestionPageVo vo = new GetQuestionPageVo();
                    BeanUtils.copyProperties(question, vo);
                    Question useQuestion = questionDao.getUseQuestion(userId, question.getId());
                    if (useQuestion == null) {
                        vo.setIsUse(false);
                    } else {
                        vo.setIsUse(true);
                    }
                    FavoritesQuestion favoritesQuestion = favoritesQuestionDao.getCorrectQuestion(userId, question.getId());
                    if (favoritesQuestion == null) {
                        vo.setCollect(false);
                    } else {
                        vo.setCollect(true);
                    }
                    vos.add(vo);
                }
                PageQuery<GetQuestionPageVo> query = new PageQuery<>();
                query.setPageNumber(pageQuery.getPageNumber());
                query.setPageSize(pageQuery.getPageSize());
                query.setList(vos);
                query.setTotalRow(pageQuery.getTotalRow());
                return GlobalReponse.success(query);
            } else {
                pageQuery.setPara("userId", userId);
                questionDao.getTaoxueFavorite(pageQuery);
                List<GetQuestionPageVo> vos = new ArrayList<>();
                for (Question question : pageQuery.getList()) {
                    GetQuestionPageVo vo = new GetQuestionPageVo();
                    BeanUtils.copyProperties(question, vo);
                    vo.setHouseType(0);
                    Question useQuestion = questionDao.getUseQuestion(userId, question.getId());
                    if (useQuestion == null) {
                        vo.setIsUse(false);
                    } else {
                        vo.setIsUse(true);
                    }
                    FavoritesQuestion favoritesQuestion = favoritesQuestionDao.getCorrectQuestion(userId, question.getId());
                    if (favoritesQuestion == null) {
                        vo.setCollect(false);
                    } else {
                        vo.setCollect(true);
                    }
                    vos.add(vo);
                }
                PageQuery<GetQuestionPageVo> query = new PageQuery<>();
                query.setPageNumber(pageQuery.getPageNumber());
                query.setPageSize(pageQuery.getPageSize());
                query.setList(vos);
                query.setTotalRow(pageQuery.getTotalRow());
                return GlobalReponse.success(query);
            }
        }
        if (dto.getType() == 2) {//共享题库
            PageQuery<Question> pageQuery = new PageQuery<>();
            pageQuery.setPageNumber(dto.getPageNo());
            pageQuery.setPageSize(10);
            pageQuery.setPara("subjectId", dto.getSubjectId());
            pageQuery.setPara("gradeId", dto.getGradeId());
            pageQuery.setPara("title", dto.getTitle());
            pageQuery.setPara("status", dto.getStatus());
            if (dto.getSubjectId() != 0) {
                questionDao.getGongxiangPage(pageQuery);
                List<GetQuestionPageVo> vos = new ArrayList<>();
                for (Question question : pageQuery.getList()) {
                    GetQuestionPageVo vo = new GetQuestionPageVo();
                    BeanUtils.copyProperties(question, vo);
                    vo.setHouseType(0);
                    if (question.getPushStatus().equals(1)) {
                        User user = userDao.unique(question.getCreateBy());
                        vo.setCreateBy(user.getId().toString());
                        vo.setCreateName(user.getName());
                        vo.setCreateImage(user.getHeadImage());
                        vo.setCreateTime(question.getCreateTime());
                    }
                    Question useQuestion = questionDao.getUseQuestion(userId, question.getId());
                    if (useQuestion == null) {
                        vo.setIsUse(false);
                    } else {
                        vo.setIsUse(true);
                    }
                    FavoritesQuestion favoritesQuestion = favoritesQuestionDao.getCorrectQuestion(userId, question.getId());
                    if (favoritesQuestion == null) {
                        vo.setCollect(false);
                    } else {
                        vo.setCollect(true);
                    }
                    vos.add(vo);
                }
                PageQuery<GetQuestionPageVo> query = new PageQuery<>();
                query.setPageNumber(pageQuery.getPageNumber());
                query.setPageSize(pageQuery.getPageSize());
                query.setList(vos);
                query.setTotalRow(pageQuery.getTotalRow());
                return GlobalReponse.success(query);
            } else {
                pageQuery.setPara("userId", userId);
                questionDao.getGongxiangFavorite(pageQuery);
                List<GetQuestionPageVo> vos = new ArrayList<>();
                for (Question question : pageQuery.getList()) {
                    GetQuestionPageVo vo = new GetQuestionPageVo();
                    BeanUtils.copyProperties(question, vo);
                    vo.setHouseType(1);
                    if (question.getPushStatus().equals(1)) {
                        User user = userDao.unique(question.getCreateBy());
                        vo.setCreateBy(user.getId().toString());
                        vo.setCreateName(user.getName());
                        vo.setCreateImage(user.getHeadImage());
                        vo.setCreateTime(question.getCreateTime());
                    }
                    Question useQuestion = questionDao.getUseQuestion(userId, question.getId());
                    if (useQuestion == null) {
                        vo.setIsUse(false);
                    } else {
                        vo.setIsUse(true);
                    }
                    FavoritesQuestion favoritesQuestion = favoritesQuestionDao.getCorrectQuestion(userId, question.getId());
                    if (favoritesQuestion == null) {
                        vo.setCollect(false);
                    } else {
                        vo.setCollect(true);
                    }
                    vos.add(vo);
                }
                PageQuery<GetQuestionPageVo> query = new PageQuery<>();
                query.setPageNumber(pageQuery.getPageNumber());
                query.setPageSize(pageQuery.getPageSize());
                query.setList(vos);
                query.setTotalRow(pageQuery.getTotalRow());
                return GlobalReponse.success(query);
            }
        }
        return GlobalReponse.fail("查询失败");
    }

    /**
     * 加入或取消收藏
     *
     * @param type
     * @param questionId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse addOrCancelFavorites(Integer type, Long questionId, Long userId) {
        //取消收藏
        if (type == 0) {
            FavoritesQuestion f = new FavoritesQuestion();
            f.setQuestionId(questionId);
            f.setUserId(userId);
            f.setIsDeleted(false);
            FavoritesQuestion favoritesQuestion = favoritesQuestionDao.templateOne(f);
            favoritesQuestion.setIsDeleted(true);
            favoritesQuestion.setUpdateBy(userId.toString());
            favoritesQuestion.setUpdateTime(new Date());
            favoritesQuestionDao.updateById(favoritesQuestion);
            return GlobalReponse.success("取消收藏成功");
        }
        //加入收藏
        if (type == 1) {
            FavoritesQuestion f = new FavoritesQuestion();
            f.setQuestionId(questionId);
            f.setUserId(userId);
            f.setIsDeleted(false);
            FavoritesQuestion favoritesQuestion = favoritesQuestionDao.templateOne(f);
            if (favoritesQuestion != null) {
                return GlobalReponse.success("该题已加入收藏");
            }
            Question question = questionDao.unique(questionId);
            Grade grade = gradeDao.getGrade(questionId);
            Subject subject = subjectDao.unique(question.getSubjectId());
            Module module = moduleDao.getModule(questionId);
            FavoritesQuestion favorites = new FavoritesQuestion();
            if (module != null) {
                favorites.setModuleId(module.getId());
            }
            favorites.setUserId(userId);
            favorites.setQuestionId(questionId);
            favorites.setType(question.getType());
            favorites.setGradeId(grade.getId());
            favorites.setGradeName(grade.getName());
            favorites.setSubjectId(subject.getId());
            favorites.setSubjectName(subject.getName());
            if (question.getWarehouseType() == 0) {
                favorites.setBackType(1);
            }
            if (question.getWarehouseType() == 1 && question.getShareType() == 1) {
                favorites.setBackType(2);
            }
            favorites.setIsDeleted(false);
            favorites.setCreateBy(userId.toString());
            favorites.setCreateTime(new Date());
            favoritesQuestionDao.insertTemplate(favorites);
            return GlobalReponse.success("加入收藏成功");
        }
        return GlobalReponse.fail("操作失败");
    }

    /**
     * 添加题目
     *
     * @param dto
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse addQuestion(AddQuestionDto dto, Long userId) {
        if (dto.getImages() != null && !dto.getImages().equals("")) {
            for (String img : dto.getImages().split(",")) {
                Boolean flag = aLiYunUtils.aliyunImageSyncCheck(img);
                if (!flag) {
                    return GlobalReponse.fail("图片存在违规信息，请更换图片后重新上传");
                }
            }
        }
        Integer check = CommentUtil.checkComment(dto.getTitle());
        if (check == 0) {
            return GlobalReponse.fail("标题存在敏感词，请重新发布");
        }
        if (dto.getId() != null) {
            Question question = questionDao.unique(dto.getId());
            BeanUtils.copyProperties(dto, question);
            ArrayList<ContentDto> dtos = new ArrayList<>();
            Integer num = 1;
            Map map = PinyinUtil.getMap();
            for (ContentDto contentDto : dto.getContentDtos()) {
                if (contentDto.getContent().equals(dto.getAnswer())) {
                    contentDto.setIsCorrect(true);
                    question.setAnswer(map.get(num).toString());
                } else {
                    contentDto.setIsCorrect(false);
                }
                num += 1;
                dtos.add(contentDto);
            }
            String jsonString = JSONObject.toJSONString(dtos);
            question.setContent(jsonString);
            if (dto.getType() == 0) {
                question.setType(QuestionType.DANXUANTI);
            } else if (dto.getType() == 1) {
                question.setType(QuestionType.ZHUGUANTI);
            } else if (dto.getType() == 2) {
                question.setType(QuestionType.XIANXIATI);
            }
            question.setCreateBy(userId.toString());
            question.setPushStatus(1);
            question.setCreateTime(new Date());
            question.setIsDeleted(false);
            question.setWarehouseType(1);
            questionDao.updateTemplateById(question);
            questionDao.deleteQuestionGrade(question.getId());
            questionDao.insertQuestionGrade(question.getId(), dto.getGradeId());
            return GlobalReponse.success("编辑成功");
        }
        Question question = new Question();
        BeanUtils.copyProperties(dto, question);
        ArrayList<ContentDto> dtos = new ArrayList<>();
        if (dto.getType() == 0) {
            Integer num = 1;
            Map map = PinyinUtil.getMap();
            for (ContentDto contentDto : dto.getContentDtos()) {
                if (contentDto.getContent() != null && !contentDto.getContent().equals("")) {
                    if (contentDto.getContent().equals(dto.getAnswer())) {
                        contentDto.setIsCorrect(true);
                        question.setAnswer(map.get(num).toString());
                    } else {
                        contentDto.setIsCorrect(false);
                    }
                    num += 1;
                    dtos.add(contentDto);
                }
            }
        } else {
            question.setContent(null);
        }
        String jsonString = JSONObject.toJSONString(dtos);
        question.setContent(jsonString);
        if (dto.getType() == 0) {
            question.setType(QuestionType.DANXUANTI);
        } else if (dto.getType() == 1) {
            question.setType(QuestionType.ZHUGUANTI);
        } else if (dto.getType() == 2) {
            question.setType(QuestionType.XIANXIATI);
        }
        question.setCreateBy(userId.toString());
        question.setCreateTime(new Date());
        question.setPushStatus(1);
        question.setIsDeleted(false);
        question.setStatus(1);
        question.setWarehouseType(1);
        questionDao.insertTemplate(question, true);
        questionDao.insertQuestionGrade(question.getId(), dto.getGradeId());
        return GlobalReponse.success("添加成功");
    }

    /**
     * 删除题目
     *
     * @param questionId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse deletedQuestion(Long questionId, Long userId) {
        Question question = questionDao.unique(questionId);
        question.setIsDeleted(true);
        question.setUpdateBy(userId.toString());
        question.setUpdateTime(new Date());
        questionDao.updateById(question);
        questionDao.deleteQuestionGrade(questionId);
        return GlobalReponse.success("删除成功");
    }

    /**
     * 获取题目详情
     *
     * @param questionId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<QuestionDetailDto> getQuestionDetail(Long questionId, Long userId) {
        Question question = questionDao.unique(questionId);
        FavoritesQuestion favorites = favoritesQuestionDao.createLambdaQuery().andEq(FavoritesQuestion::getQuestionId, questionId).andEq(FavoritesQuestion::getUserId, userId).andEq(FavoritesQuestion::getIsDeleted, false).single();
        Grade grade = gradeDao.getGrade(questionId);
        Subject subject = subjectDao.unique(question.getSubjectId());
        QuestionDetailDto detailDto = new QuestionDetailDto();
        BeanUtils.copyProperties(question, detailDto);
        List<ContentDto> ts = JSONArray.parseArray(question.getContent(), ContentDto.class);
        detailDto.setContentDtos(ts);
        detailDto.setGradeName(grade.getName());
        detailDto.setSubjectName(subject.getName());
        if (question.getWarehouseType() == 1) {
            User user = userDao.unique(question.getCreateBy());
            detailDto.setCreateId(user.getId());
            detailDto.setCreateName(user.getName());
            detailDto.setCreateImage(user.getHeadImage());
            if (Long.valueOf(question.getCreateBy()).equals(userId)) {
                detailDto.setIsMy(true);
            } else {
                detailDto.setIsMy(false);
            }
        }
        if (favorites != null) {
            detailDto.setIsFavorites(true);
        } else {
            detailDto.setIsFavorites(false);
        }
        QuestionVo questionVo = QuestionVoMapper.MAPPER.toVo(question);
        detailDto.set("optionList", questionVo.getOptionList());
        return GlobalReponse.success(detailDto);
    }

    /**
     * 获取作业名称
     *
     * @return
     */
    @Override
    public GlobalReponse<JobNameDto> getJobName() {
        List<JobName> jobNames = jobNameDao.createLambdaQuery().andEq(JobName::getIsDeleted, false).select();
        ArrayList<JobNameDto> dtos = new ArrayList<>();
        if (jobNames.isEmpty()) {
            return GlobalReponse.success("暂无名称，请手动输入");
        }
        for (JobName jobName : jobNames) {
            JobNameDto dto = new JobNameDto();
            dto.setId(jobName.getId());
            dto.setName(jobName.getName());
            dtos.add(dto);
        }
        return GlobalReponse.success(dtos);
    }

    /**
     * 获取截止时间
     *
     * @return
     */
    @Override
    public GlobalReponse getDeadline() {
        JobParameter single = jobParameterDao.createLambdaQuery().andEq(JobParameter::getIsDeleted, false).single();
        String minute = single.getMinute();
        return GlobalReponse.success(minute);
    }

    /**
     * 布置作业
     *
     * @param homeworkDto
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse putHomework(HomeworkDto homeworkDto, Long userId) {
        Job job = new Job();
        job.setName(homeworkDto.getJobName());
        job.setSubjectId(homeworkDto.getSubjectId());
        job.setDeadline(homeworkDto.getDeadline());
        job.setCreateBy(userId.toString());
        job.setCreateTime(new Date());
        job.setIsDeleted(false);
        job.setQuestionNum(Long.valueOf(homeworkDto.getQuestionIds().length));
        BigDecimal score = new BigDecimal(0);
        for (Long questionId : homeworkDto.getQuestionIds()) {
            Question question = questionDao.unique(questionId);
            score = score.add(question.getScore());
        }
        job.setScore(score);
        jobDao.insertTemplate(job, true);


        for (Long classId : homeworkDto.getClassIds()) {
            ClassJob classJob = new ClassJob();
            classJob.setClassId(classId);
            classJob.setJobId(job.getId());
            classJob.setCreateBy(userId.toString());
            classJob.setCreateTime(new Date());
            classJob.setIsDeleted(false);
            classJobDao.insertTemplate(classJob);
        }

        Long serialNumber = 1L;
        for (Long questionId : homeworkDto.getQuestionIds()) {
            JobQuestion jobQuestion = new JobQuestion();
            jobQuestion.setSerialNumber(serialNumber);
            jobQuestion.setClassJobId(job.getId());
            jobQuestion.setQuestionId(questionId);
            jobQuestion.setCreateBy(userId.toString());
            jobQuestion.setCreateTime(new Date());
            jobQuestion.setIsDeleted(false);
            jobQuestionDao.insertTemplate(jobQuestion);
            serialNumber += 1;
        }

        for (Long classId : homeworkDto.getClassIds()) {
            ClassMembers classMembers = new ClassMembers();
            classMembers.setIsDeleted(false);
            classMembers.setClassId(classId);
            classMembers.setType(1);
            List<ClassMembers> template = classMembersDao.template(classMembers);
            for (ClassMembers members : template) {
                UserJob userJob = new UserJob();
                userJob.setClassId(classId);
                userJob.setUserId(members.getUserId());
                userJob.setJobId(job.getId());
                userJob.setStatus(0);
                userJob.setCreateBy(userId.toString());
                userJob.setCreateTime(new Date());
                userJob.setIsDeleted(false);
                userJobDao.insertTemplate(userJob);
            }
        }
        return GlobalReponse.success("布置作业成功");
    }

    /**
     * 获取题目最大的分数
     *
     * @return
     */
    @Override
    public GlobalReponse getScore() {
        JobParameter single = jobParameterDao.createLambdaQuery().andEq(JobParameter::getIsDeleted, false).single();
        return GlobalReponse.success(single.getScore());
    }

    /**
     * 通过班级id多条件查看作业列表
     *
     * @param jobConditionDto
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<JobDto>> getJobListById(JobConditionDto jobConditionDto, Long userId) {
        PageQuery<Job> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(jobConditionDto.getPageNo());
        pageQuery.setPageSize(10);
        pageQuery.setPara("classId", jobConditionDto.getClassId());
        pageQuery.setPara("pushTime", jobConditionDto.getPushTime());
        pageQuery.setPara("entTime", jobConditionDto.getEntTime());
        pageQuery.setPara("subjectName", jobConditionDto.getSubjectName());
        pageQuery.setPara("sort", jobConditionDto.getSort());
        pageQuery.setPara("isMy", jobConditionDto.getIsMy());
        pageQuery.setPara("userId", userId);
        if (jobConditionDto.getPushTime() != null && jobConditionDto.getPushTime() == 5) {
            pageQuery.setPara("startTime", jobConditionDto.getStartTime());
            pageQuery.setPara("finishTime", jobConditionDto.getFinishTime());
        }
        if (jobConditionDto.getPushTime() != null && jobConditionDto.getPushTime() == 4) {
            ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
            //判断上下学期
            String now = new SimpleDateFormat("MM-dd").format(new Date());
            String spring = classParam.getSpringTime();
            String autumn = classParam.getAutumnTime();
            Date nowTime = null;
            Date springTime = null;
            Date autumnTime = null;
            try {
                nowTime = DateUtils.parseDate(now, "MM-dd");
                springTime = DateUtils.parseDate(spring, "MM-dd");
                autumnTime = DateUtils.parseDate(autumn, "MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar cal = Calendar.getInstance();
            int yearD = cal.get(Calendar.YEAR);

            if (nowTime.after(autumnTime) && nowTime.before(springTime)) {
                pageQuery.setPara("startTime", yearD + "-" + classParam.getAutumnTime());
                pageQuery.setPara("finishTime", yearD + "-" + classParam.getSpringTime());
            } else {
                pageQuery.setPara("startTime", yearD + "-" + classParam.getSpringTime());
                pageQuery.setPara("finishTime", yearD + 1 + "-" + classParam.getAutumnTime());
            }
        }

        jobDao.getJobListById(pageQuery);
        List<JobDto> dtos = new ArrayList<>();
        for (Job job : pageQuery.getList()) {
            JobDto jobDto = new JobDto();
            jobDto.setJobId(job.getId());
            jobDto.setJobName(job.getName());
            jobDto.setDeadline(job.getDeadline());
            jobDto.setDeadlineTime(job.getDeadline().getTime());
            User user = userDao.unique(Long.valueOf(job.getCreateBy()));
            jobDto.setPusherId(user.getId());
            ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, jobConditionDto.getClassId()).andEq(ClassMembers::getUserId, user.getId()).andEq(ClassMembers::getIsDeleted, false).single();
            if (single != null && single.getNickname() != null) {
                jobDto.setPusherName(single.getNickname());
            } else {
                jobDto.setPusherName(user.getName());
            }
            if (user.getHeadImage() != null) {
                jobDto.setPusherImage(user.getHeadImage());
            }
            Subject subject = subjectDao.unique(job.getSubjectId());
            jobDto.setSubjectName(subject.getName());
            //学生数量
            long studentCount = classMembersDao.createLambdaQuery().andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).andEq(ClassMembers::getClassId, jobConditionDto.getClassId()).count();
            jobDto.setStudentNum(studentCount);
            //学生的作业
            List<UserJob> userJobs = userJobDao.createLambdaQuery().andEq(UserJob::getClassId, jobConditionDto.getClassId()).andEq(UserJob::getJobId, job.getId()).andEq(UserJob::getIsDeleted, false).select();

            //题目总数
            List<JobQuestion> jobQuestions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, job.getId()).andEq(JobQuestion::getIsDeleted, false).select();
            jobDto.setTopicNum(Long.valueOf(jobQuestions.size()));
            //是否过截止时间
            if (new Date().getTime() > job.getDeadline().getTime()) {
                jobDto.setIsDeadline(true);
            } else {
                jobDto.setIsDeadline(false);
            }

            //学生得分
            BigDecimal studentScore = new BigDecimal(0);
            Long correctNum = 0L;
            Long noCorrectNum = 0L;
            Long submitNum = 0L;
            Long noSubmitNum = 0L;

            List<Question> questions = questionDao.getJobQuestion(job.getId());
            List<QuestionType> types = questions.stream().map(Question::getType).collect(Collectors.toList());
            ArrayList<Integer> integers = new ArrayList<>();
            for (QuestionType type : types) {
                Integer value = type.getValue();
                integers.add(value);
            }

            List<Integer> statusList = userJobs.stream().map(UserJob::getStatus).collect(Collectors.toList());
            if (statusList.size() > 0) {
                if (statusList.contains(1)) {
                    if (!integers.contains(1) && !integers.contains(2)) {
                        jobDto.setStatus(-1);
                    } else {
                        jobDto.setStatus(1);
                    }
                } else if (!statusList.contains(0) && !statusList.contains(1)) {
                    if (!integers.contains(1) && !integers.contains(2)) {
                        jobDto.setStatus(-1);
                    } else {
                        jobDto.setStatus(2);
                    }
                } else if (statusList.contains(0) && !statusList.contains(1)) {
                    jobDto.setStatus(0);
                }
            } else {
                jobDto.setStatus(0);
            }

            for (UserJob userJob : userJobs) {
                if (userJob.getScore() != null) {
                    studentScore = studentScore.add(userJob.getScore());
                }
                if (userJob.getStatus() != 0) {
                    submitNum += 1;
                    if (userJob.getScore() != null && userJob.getScore().compareTo(job.getScore()) == 0) {
                        correctNum += 1;
                    } else {
                        noCorrectNum += 1;
                    }
                } else {
                    noSubmitNum += 1;
                }
            }
            jobDto.setSubmit(submitNum);
            jobDto.setNoSubmit(noSubmitNum);
            jobDto.setCorrectNum(correctNum);
            jobDto.setNoCorrectNum(noCorrectNum);

            //平均正确率
            if (!studentScore.equals(BigDecimal.ZERO) && studentCount != 0) {
                BigDecimal score = job.getScore().multiply(new BigDecimal(studentCount));
                jobDto.setAccuracy(studentScore.divide(job.getScore().multiply(new BigDecimal(studentCount)), 4).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            } else {
                jobDto.setAccuracy("0");
            }
            dtos.add(jobDto);
        }
        PageQuery<JobDto> dtoPageQuery = new PageQuery<>();
        dtoPageQuery.setList(dtos);
        dtoPageQuery.setPageSize(pageQuery.getPageSize());
        dtoPageQuery.setPageNumber(pageQuery.getPageNumber());
        dtoPageQuery.setTotalRow(pageQuery.getTotalRow());

        return GlobalReponse.success(dtoPageQuery);
    }

    /**
     * 根据id查看作业详情
     *
     * @param jobId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<JobDto> getJobDetails(Long classId, Long jobId, Long userId) {
        Job job = jobDao.unique(jobId);
        ClassJob classJob = classJobDao.createLambdaQuery().andEq(ClassJob::getJobId, jobId).andEq(ClassJob::getClassId, classId).andEq(ClassJob::getIsDeleted, false).single();
        JobDto jobDto = new JobDto();
        jobDto.setJobId(job.getId());
        jobDto.setJobName(job.getName());
        jobDto.setDeadline(job.getDeadline());
        jobDto.setDeadlineTime(job.getDeadline().getTime());
        User user = userDao.unique(Long.valueOf(job.getCreateBy()));
        jobDto.setPusherId(user.getId());
        ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classJob.getClassId()).andEq(ClassMembers::getUserId, user.getId()).andEq(ClassMembers::getIsDeleted, false).single();
        if (single != null && single.getNickname() != null) {
            jobDto.setPusherName(single.getNickname());
        } else {
            jobDto.setPusherName(user.getName());
        }
        if (user.getHeadImage() != null) {
            jobDto.setPusherImage(user.getHeadImage());
        }
        Subject subject = subjectDao.unique(job.getSubjectId());
        jobDto.setSubjectName(subject.getName());
        //学生数量
        long studentCount = classMembersDao.createLambdaQuery().andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).andEq(ClassMembers::getClassId, classJob.getClassId()).count();
        jobDto.setStudentNum(studentCount);
        //学生的作业
        List<UserJob> userJobs = userJobDao.createLambdaQuery().andEq(UserJob::getClassId, classId).andEq(UserJob::getJobId, job.getId()).andEq(UserJob::getIsDeleted, false).select();

        List<Integer> statusList = userJobs.stream().map(UserJob::getStatus).collect(Collectors.toList());
        if (statusList.size() > 0) {
            if (statusList.contains(1)) {
                jobDto.setStatus(1);
            }
            if (!statusList.contains(0) && !statusList.contains(1)) {
                jobDto.setStatus(2);
            }
        } else {
            jobDto.setStatus(0);
        }

        //学生得分
        BigDecimal studentScore = new BigDecimal(0);
        Long correctNum = 0L;
        Long allTime = 0L;
        Long noCorrectNum = 0L;
        Long submitNum = 0L;
        Long noSubmitNum = 0L;
        for (UserJob userJob : userJobs) {
            if (userJob.getUseTime() != null) {
                allTime += userJob.getUseTime();
            }
            if (userJob.getScore() != null) {
                studentScore = studentScore.add(userJob.getScore());
            }
            if (userJob.getStatus() != 0) {
                submitNum += 1;
                if (userJob.getScore() != null && userJob.getScore().compareTo(job.getScore()) == 0) {
                    correctNum += 1;
                } else {
                    noCorrectNum += 1;
                }
            } else {
                noSubmitNum += 1;
            }
        }
        jobDto.setSubmit(submitNum);
        jobDto.setNoSubmit(noSubmitNum);
        jobDto.setCorrectNum(correctNum);
        jobDto.setNoCorrectNum(noCorrectNum);

        //平均正确率
        if (!studentScore.equals(BigDecimal.ZERO) && studentCount != 0) {
            jobDto.setAccuracy(studentScore.divide(job.getScore().multiply(new BigDecimal(studentCount)), 4).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
        } else {
            jobDto.setAccuracy("0");
        }

        //平均用时
        if (!allTime.equals(0) && studentCount != 0L) {
            long avgTime = allTime * 1000L / studentCount;
            jobDto.setAverageTime(avgTime);
        } else {
            jobDto.setAverageTime(null);
        }

        if (new Date().getTime() > job.getDeadline().getTime()) {
            jobDto.setIsDeadline(true);
        } else {
            jobDto.setIsDeadline(false);
        }

        //题目总数
        List<JobQuestion> questions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, job.getId()).andEq(JobQuestion::getIsDeleted, false).select();
        jobDto.setTopicNum(Long.valueOf(questions.size()));

        //是否有主观题需要修改
        if (job.getCreateBy().equals(userId.toString())) {
            jobDto.setIsMy(true);
            List<Long> ids = questions.stream().map(JobQuestion::getQuestionId).collect(Collectors.toList());
            List<Question> select = questionDao.createLambdaQuery().andIn(Question::getId, ids).andEq(Question::getIsDeleted, false).andNotEq(Question::getType, 0).select();
            List<Long> zIds = select.stream().map(Question::getId).collect(Collectors.toList());
            if (!zIds.isEmpty()) {
                List<QuestionRecord> questionRecords = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getJobId, jobId).andIn(QuestionRecord::getQuestionId, zIds).andEq(QuestionRecord::getIsCheck, false).andEq(QuestionRecord::getIsDeleted, false).select();
                if (!questionRecords.isEmpty()) {
                    jobDto.setIsCheck(true);
                } else {
                    jobDto.setIsCheck(false);
                }
            }
        } else {
            jobDto.setIsMy(false);
        }

        return GlobalReponse.success(jobDto);
    }

    /**
     * 教师端查看排行榜
     *
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<UserJobVo>> getRankTeacher(GetRankDto dto) {
        if (dto.getPageNo() == null || dto.getPageNo() == 0) {
            dto.setPageNo(1);
        }
        Job job = jobDao.unique(dto.getJobId());
        PageQuery<UserJob> query = new PageQuery<>();
        query.setPageNumber(dto.getPageNo());
        query.setPageSize(10);
        query.setPara("type", dto.getType());
        JobParameter single = jobParameterDao.createLambdaQuery().andEq(JobParameter::getIsDeleted, false).single();
        BigDecimal passScore = job.getScore().multiply(single.getAccuracy().divide(new BigDecimal(100)));
        query.setPara("passScore", passScore);
        query.setPara("classId", dto.getClassId());
        query.setPara("jobId", dto.getJobId());
        userJobDao.getRankTeacher(query);
        Long rank = 0L;
        List<UserJobVo> vos = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        for (UserJob userJob : query.getList()) {
            UserJobVo vo = new UserJobVo();
            vo.setJobId(userJob.getJobId());
            vo.setScore(userJob.getScore());
            User user = userDao.unique(userJob.getUserId());
            vo.setUserId(user.getId());
            vo.setUserName(user.getName());
            vo.setHeadImage(user.getHeadImage());
            vo.setUseTime(userJob.getUseTime());
            vo.setElapsedTime(userJob.getUseTime() * 1000L);
            if (userJob.getFinishTime() != null) {
                vo.setFinishTime(format.format(userJob.getFinishTime()));
            }
            vo.setStatus(userJob.getStatus());
            vo.setRank(rank += 1);
            vos.add(vo);
        }
        PageQuery<UserJobVo> voPageQuery = new PageQuery<>();
        voPageQuery.setPageSize(query.getPageSize());
        voPageQuery.setPageNumber(query.getPageNumber());
        voPageQuery.setTotalRow(query.getTotalRow());
        voPageQuery.setList(vos);
        return GlobalReponse.success(voPageQuery);
    }

    /**
     * 查询作业题目数量
     *
     * @param jobId
     * @return
     */
    @Override
    public GlobalReponse<QuestionCountDto> getJobQuestionCount(Long jobId) {
        List<JobQuestion> jobQuestions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, jobId).andEq(JobQuestion::getIsDeleted, false).select();
        List<Long> ids = jobQuestions.stream().map(JobQuestion::getQuestionId).collect(Collectors.toList());
        QuestionCountDto questionCountDto = new QuestionCountDto();
        //全部
        long all = questionDao.createLambdaQuery().andIn(Question::getId, ids).count();
        questionCountDto.setAllNum(all);

        //单选
        long dan = questionDao.createLambdaQuery().andIn(Question::getId, ids).andEq(Question::getType, QuestionType.DANXUANTI).count();
        questionCountDto.setChoiceNum(dan);

        //主观
        long zhu = questionDao.createLambdaQuery().andIn(Question::getId, ids).andEq(Question::getType, QuestionType.ZHUGUANTI).count();
        questionCountDto.setSubjectiveNum(zhu);

        //线下
        long xian = questionDao.createLambdaQuery().andIn(Question::getId, ids).andEq(Question::getType, QuestionType.XIANXIATI).count();
        questionCountDto.setOfflineNum(xian);
        return GlobalReponse.success(questionCountDto);
    }

    /**
     * 查询作业题目列表
     *
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<JobQuestionDto>> getJobQuestionPage(GetJobQuestionPageDto dto) {
        if (dto.getPageNo() == null || dto.getPageNo() == 0) {
            dto.setPageNo(1);
        }
        PageQuery<JobQuestionDto> query = new PageQuery<>();
        query.setPageNumber(dto.getPageNo());
        query.setPageSize(10);
        query.setPara("classId", dto.getClassId());
        query.setPara("jobId", dto.getJobId());
//        query.setPara("status", dto.getStatus());
//        query.setPara("sort", dto.getSort());
        query.setPara("type", dto.getType());
        questionDao.getJobQuestionPage(query);

        List<ClassMembers> classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, dto.getClassId()).andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).select();
        for (JobQuestionDto question : query.getList()) {
            Question unique = questionDao.unique(question.getId());
            List<QuestionRecord> questionRecords = questionRecordDao.getJobQuestionPage(dto.getClassId(), dto.getJobId(), unique.getId());
            BigDecimal bigDecimal = new BigDecimal(0);
            question.setIsCheck(false);
            if (questionRecords.size() != 0) {
                List<Boolean> collect = questionRecords.stream().map(QuestionRecord::getIsCheck).collect(Collectors.toList());
                if (!collect.contains(false)) {
                    question.setIsCheck(true);
                }
                for (QuestionRecord questionRecord : questionRecords) {
                    if (questionRecord.getScore() != null) {
                        bigDecimal = bigDecimal.add(questionRecord.getScore());
                    }
                }
            }
            if (classMembers.size() > 0) {
                question.setAccuracy(bigDecimal.divide(new BigDecimal(classMembers.size()).multiply(unique.getScore()), 0).multiply(new BigDecimal(100)));
            } else {
                question.setAccuracy(new BigDecimal(0));
            }
        }
        if (dto.getStatus() != null) {
            ArrayList<JobQuestionDto> jobQuestionDtos = new ArrayList<>();
            for (JobQuestionDto jobQuestionDto : query.getList()) {
                if (dto.getStatus() == 0) {
                    if (jobQuestionDto.getAccuracy() != null && jobQuestionDto.getAccuracy() == new BigDecimal(100)) {
                        jobQuestionDtos.add(jobQuestionDto);
                    }
                }
                if (dto.getStatus() == 1) {
                    if (jobQuestionDto.getIsCheck() != null && jobQuestionDto.getIsCheck() == false) {
                        jobQuestionDtos.add(jobQuestionDto);
                    }
                }
            }
            query.setList(jobQuestionDtos);
        }
        if (dto.getSort() == null) {
            dto.setSort(0);
        } else {
            if (dto.getSort() == 0) {
                List<JobQuestionDto> list = query.getList();
                List<JobQuestionDto> collect = list.stream().sorted(Comparator.comparing(JobQuestionDto::getAccuracy)).collect(Collectors.toList());
                query.setList(collect);
            } else {
                List<JobQuestionDto> list = query.getList();
                List<JobQuestionDto> collect = list.stream().sorted(Comparator.comparing(JobQuestionDto::getAccuracy).reversed()).collect(Collectors.toList());
                query.setList(collect);
            }
        }
        return GlobalReponse.success(query);
    }

    /**
     * 通过班级和作业获取题目详情
     *
     * @param classId
     * @param questionId
     * @return
     */
    @Override
    public GlobalReponse<QuestionDetailDto> getQuestionDetailFromJob(Long classId, Long jobId, Long questionId) {
        List<ClassMembers> classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).select();
        List<Long> userIds = classMembers.stream().map(ClassMembers::getUserId).collect(Collectors.toList());
        Question question = questionDao.unique(questionId);
        QuestionDetailDto dto = new QuestionDetailDto();
        BeanUtils.copyProperties(question, dto);
        Grade grade = gradeDao.getGrade(question.getId());
        Subject subject = subjectDao.unique(question.getSubjectId());
        if (question.getWarehouseType() == 1) {
            User user = userDao.unique(question.getCreateBy());
            dto.setCreateId(user.getId());
            dto.setCreateName(user.getName());
            dto.setCreateStatus(user.getIsLocked());
            dto.setCreateImage(user.getHeadImage());
        }
        dto.setGradeName(grade.getName());
        dto.setSubjectName(subject.getName());

        if (userIds.size() != 0) {
            //全对/答对
            List<QuestionRecord> answerList = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getClassId, classId).andEq(QuestionRecord::getStatus, 1).andEq(QuestionRecord::getIsDeleted, false).andIn(QuestionRecord::getUserId, userIds).andEq(QuestionRecord::getScore, question.getScore()).andEq(QuestionRecord::getQuestionId, questionId).andEq(QuestionRecord::getIsCheck, true).andEq(QuestionRecord::getJobId, jobId).select();
            ArrayList<User> answerUsers = new ArrayList<>();
            for (QuestionRecord record : answerList) {
                User user = userDao.unique(record.getUserId());
                user.set("score", record.getScore());
                user.set("userAnswer", record.getUserAnswer());
                answerUsers.add(user);
            }
            dto.setAnswerList(answerUsers);

            //未答
            List<QuestionRecord> unansweredList = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getClassId, classId).andEq(QuestionRecord::getStatus, 1).andEq(QuestionRecord::getIsDeleted, false).andEq(QuestionRecord::getJobId, jobId).andEq(QuestionRecord::getQuestionId, questionId).andIn(QuestionRecord::getUserId, userIds).select();
            List<Long> ids = unansweredList.stream().map(QuestionRecord::getUserId).collect(Collectors.toList());
            ArrayList<Long> longs = new ArrayList<>();
            longs.addAll(userIds);
            longs.removeAll(ids);
            ArrayList<User> unansweredUserList = new ArrayList<>();
            for (Long aLong : longs) {
                User user = userDao.unique(aLong);
                unansweredUserList.add(user);
            }
            dto.setUnansweredList(unansweredUserList);

            //答错
            List<QuestionRecord> wrongList = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getClassId, classId).andEq(QuestionRecord::getStatus, 1).andEq(QuestionRecord::getIsDeleted, false).andEq(QuestionRecord::getJobId, jobId).andEq(QuestionRecord::getQuestionId, questionId).andIn(QuestionRecord::getUserId, userIds).andEq(QuestionRecord::getScore, 0).andEq(QuestionRecord::getIsCheck, true).select();
            ArrayList<User> wrongUsers = new ArrayList<>();
            for (QuestionRecord record : wrongList) {
                User user = userDao.unique(record.getUserId());
                user.set("userAnswer", record.getUserAnswer());
                wrongUsers.add(user);
            }
            dto.setWrongList(wrongUsers);

            if (question.getType() != QuestionType.DANXUANTI) {
                //半对
                List<QuestionRecord> halfList = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getClassId, classId).andEq(QuestionRecord::getStatus, 1).andEq(QuestionRecord::getIsDeleted, false).andEq(QuestionRecord::getJobId, jobId).andEq(QuestionRecord::getQuestionId, questionId).andIn(QuestionRecord::getUserId, userIds).andIsNotNull(QuestionRecord::getScore).andEq(QuestionRecord::getIsCheck, true).andGreat(QuestionRecord::getScore, 0).andLess(QuestionRecord::getScore, question.getScore()).select();
                ArrayList<User> halfUsers = new ArrayList<>();
                for (QuestionRecord record : halfList) {
                    User user = userDao.unique(record.getUserId());
                    user.set("score", record.getScore());
                    user.set("userAnswer", record.getUserAnswer());
                    halfUsers.add(user);
                }
                dto.setHalfList(halfUsers);

                //未打分
                List<QuestionRecord> notScoreList = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getClassId, classId).andEq(QuestionRecord::getStatus, 1).andEq(QuestionRecord::getIsDeleted, false).andEq(QuestionRecord::getJobId, jobId).andEq(QuestionRecord::getQuestionId, questionId).andIn(QuestionRecord::getUserId, userIds).andEq(QuestionRecord::getIsCheck, false).select();
                ArrayList<User> notScoreUsers = new ArrayList<>();
                for (QuestionRecord record : notScoreList) {
                    User user = userDao.unique(record.getUserId());
                    user.set("userAnswer", record.getUserAnswer());
                    notScoreUsers.add(user);
                }
                dto.setNotScoreList(notScoreUsers);

            }
        }

        return GlobalReponse.success(dto);
    }

    /**
     * 通过作业Id查看全部班级
     *
     * @param jobId
     * @return
     */
    @Override
    public GlobalReponse<JobDto> getAllClassForJobId(Long jobId, Long userId) {
        List<ClassJob> classJobs = classJobDao.createLambdaQuery().andEq(ClassJob::getJobId, jobId).andEq(ClassJob::getIsDeleted, false).select();
        List<JobDto> jobDtos = new ArrayList<>();
        for (ClassJob classJob : classJobs) {
            JobDto jobDto = new JobDto();
            Job job = jobDao.unique(classJob.getJobId());
            jobDto.setJobId(job.getId());
            jobDto.setJobName(job.getName());
            jobDto.setDeadline(job.getDeadline());
            jobDto.setDeadlineTime(job.getDeadline().getTime());
            User user = userDao.unique(Long.valueOf(job.getCreateBy()));
            jobDto.setPusherId(user.getId());
            ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classJob.getClassId()).andEq(ClassMembers::getUserId, user.getId()).single();
            if (single != null && single.getNickname() != null) {
                jobDto.setPusherName(single.getNickname());
            } else {
                jobDto.setPusherName(user.getName());
            }
            if (single != null && single.getHeadImage() != null) {
                jobDto.setPusherImage(single.getHeadImage());
            } else {
                jobDto.setPusherImage(user.getHeadImage());

            }
            Subject subject = subjectDao.unique(job.getSubjectId());
            jobDto.setSubjectName(subject.getName());
            //学生数量
            long studentCount = classMembersDao.createLambdaQuery().andEq(ClassMembers::getType, 1).andEq(ClassMembers::getIsDeleted, false).andEq(ClassMembers::getClassId, classJob.getClassId()).count();

            //学生的作业
            List<UserJob> userJobs = userJobDao.createLambdaQuery().andEq(UserJob::getClassId, classJob.getClassId()).andEq(UserJob::getJobId, job.getId()).andEq(UserJob::getIsDeleted, false).select();
//            List<Integer> statusList = userJobs.stream().map(UserJob::getStatus).collect(Collectors.toList());
//            if (statusList.size() > 0) {
//                if (statusList.contains(1)) {
//                    jobDto.setStatus(1);
//                }
//                if (!statusList.contains(0) && !statusList.contains(1)) {
//                    jobDto.setStatus(2);
//                }
//            }

            //学生得分
            BigDecimal studentScore = new BigDecimal(0);
            Long correctNum = 0L;
            Long allTime = 0L;
            Long noCorrectNum = 0L;
            Long submitNum = 0L;
            Long noSubmitNum = 0L;
            for (UserJob userJob : userJobs) {
                if (userJob.getUseTime() != null) {
                    allTime += userJob.getUseTime();
                }
                if (userJob.getScore() != null) {
                    studentScore = studentScore.add(userJob.getScore());
                }
                if (userJob.getStatus() != 0) {
                    submitNum += 1;
                    if (userJob.getScore() != null && userJob.getScore().compareTo(job.getScore()) == 0) {
                        correctNum += 1;
                    } else {
                        noCorrectNum += 1;
                    }
                } else {
                    noSubmitNum += 1;
                }
                List<QuestionRecord> questionRecords = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getUserId, userJob.getUserId()).andEq(QuestionRecord::getJobId, userJob.getJobId()).select();
                for (QuestionRecord questionRecord : questionRecords) {
                    if (questionRecord != null && questionRecord.getCorrect() != null && questionRecord.getCorrect() == null) {
                        jobDto.setStatus(1);
                    }
                }
            }
            jobDto.setSubmit(submitNum);
            jobDto.setNoSubmit(noSubmitNum);
            jobDto.setCorrectNum(correctNum);
            jobDto.setNoCorrectNum(noCorrectNum);

            //平均正确率
            if (!studentScore.equals(BigDecimal.ZERO) && studentCount != 0) {
                jobDto.setAccuracy(studentScore.divide(job.getScore().multiply(new BigDecimal(studentCount)), 4).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            } else {
                jobDto.setAccuracy("0");
            }

            //平均用时
            if (!allTime.equals(0) && studentCount != 0L) {
                long avgTime = allTime * 1000L / studentCount;
                jobDto.setAverageTime(avgTime);
            } else {
                jobDto.setAverageTime(null);
            }

            //题目总数
            List<JobQuestion> questions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, job.getId()).andEq(JobQuestion::getIsDeleted, false).select();
            jobDto.setTopicNum(Long.valueOf(questions.size()));

            //是否有主观题需要修改
//            List<Long> ids = questions.stream().map(JobQuestion::getQuestionId).collect(Collectors.toList());
//            List<Question> select = questionDao.createLambdaQuery().andIn(Question::getId, ids).andEq(Question::getIsDeleted, false).andNotEq(Question::getType, 0).select();
//            List<Long> zIds = select.stream().map(Question::getId).collect(Collectors.toList());
//            if (!zIds.isEmpty()) {
//                List<QuestionRecord> questionRecords = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getJobId, jobId).andIn(QuestionRecord::getQuestionId, zIds).andEq(QuestionRecord::getIsCheck, false).andEq(QuestionRecord::getIsDeleted, false).select();
//                if (!questionRecords.isEmpty()) {
//                    jobDto.setIsCheck(true);
//                }else {
//                    jobDto.setIsCheck(false);
//                }
//            }
//            if (job.getCreateBy().equals(userId)) {
//                jobDto.setIsMy(true);
//            } else {
//                jobDto.setIsMy(false);
//            }
            if (job.getCreateBy().equals(userId.toString())) {
                jobDto.setIsMy(true);
                List<Long> ids = questions.stream().map(JobQuestion::getQuestionId).collect(Collectors.toList());
                List<Question> select = questionDao.createLambdaQuery().andIn(Question::getId, ids).andEq(Question::getIsDeleted, false).andNotEq(Question::getType, 0).select();
                List<Long> zIds = select.stream().map(Question::getId).collect(Collectors.toList());
                if (!zIds.isEmpty()) {
                    List<QuestionRecord> questionRecords = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getJobId, jobId).andIn(QuestionRecord::getQuestionId, zIds).andEq(QuestionRecord::getIsCheck, false).andEq(QuestionRecord::getIsDeleted, false).select();
                    if (!questionRecords.isEmpty()) {
                        jobDto.setIsCheck(true);
                    } else {
                        jobDto.setIsCheck(false);
                    }
                }
            } else {
                jobDto.setIsMy(false);
            }

            ClassAnd classAnd = classAndDao.unique(classJob.getClassId());
            jobDto.set("classAnd", classAnd);
            jobDto.set("studentCount", studentCount);

            jobDtos.add(jobDto);

        }
        return GlobalReponse.success(jobDtos);
    }

    /**
     * 通过班级Id和作业Id查看学生列表
     *
     * @param classId
     * @param jobId
     * @return
     */
    @Override
    public GlobalReponse<GetAllStudentListDto> getAllStudentList(Long classId, Long jobId) {
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        List<ClassMembers> classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getType, 1).andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getIsDeleted, false).select();
        List<Long> userIds = classMembers.stream().map(ClassMembers::getUserId).collect(Collectors.toList());
        if (userIds.size() <= 0) {
            GetAllStudentListDto studentListDto = new GetAllStudentListDto();
            return GlobalReponse.success(studentListDto);
        }
        //全部集合
        Job job = jobDao.unique(jobId);
        ArrayList<UserJobVo> allVos = new ArrayList<>();
        List<UserJob> allUserJobs = userJobDao.createLambdaQuery().andEq(UserJob::getJobId, jobId).andEq(UserJob::getClassId, classId).andEq(UserJob::getClassId, classId).andIn(UserJob::getUserId, userIds).andEq(UserJob::getIsDeleted, false).select();
        for (UserJob userJob : allUserJobs) {
            ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getType, 1).andEq(ClassMembers::getUserId, userJob.getUserId()).andEq(ClassMembers::getIsDeleted, false).single();
            UserJobVo vo = new UserJobVo();
            vo.setId(userJob.getId());
            vo.setJobId(userJob.getJobId());
            vo.setUserId(single.getUserId());
            vo.setUserName(single.getNickname());
            if (single.getHeadImage() != null) {
                vo.setHeadImage(single.getHeadImage());
            } else {
                User unique = userDao.unique(single.getUserId());
                vo.setHeadImage(unique.getHeadImage());
            }
            vo.setStatus(userJob.getStatus());
            vo.setComment(userJob.getComment());
            vo.setScore(userJob.getScore());
            if (userJob.getFinishTime() != null) {
                vo.setFinishTime(format.format(userJob.getFinishTime()));
            }
            if (userJob.getScore() != null && job.getScore() != null) {
                if (userJob.getScore().equals(job.getScore())) {
                    vo.setIsRight(true);
                }
            } else {
                vo.setIsRight(false);
            }
            allVos.add(vo);
        }

        //已提交集合
        ArrayList<UserJobVo> submitVos = new ArrayList<>();
        List<UserJob> submitUserJobs = userJobDao.createLambdaQuery().andEq(UserJob::getJobId, jobId).andEq(UserJob::getClassId, classId).andIn(UserJob::getUserId, userIds).andNotEq(UserJob::getStatus, 0).andEq(UserJob::getIsDeleted, false).select();
        for (UserJob userJob : submitUserJobs) {
            ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getUserId, userJob.getUserId()).andEq(ClassMembers::getIsDeleted, false).single();
            UserJobVo vo = new UserJobVo();
            vo.setId(userJob.getId());
            vo.setJobId(userJob.getJobId());
            vo.setUserId(single.getUserId());
            vo.setUserName(single.getNickname());
            if (single.getHeadImage() != null) {
                vo.setHeadImage(single.getHeadImage());
            } else {
                User unique = userDao.unique(single.getUserId());
                vo.setHeadImage(unique.getHeadImage());
            }
            vo.setStatus(userJob.getStatus());
            vo.setComment(userJob.getComment());
            vo.setScore(userJob.getScore());
            if (userJob.getFinishTime() != null) {
                vo.setFinishTime(format.format(userJob.getFinishTime()));
            }
            if (userJob.getScore() != null && job.getScore() != null) {
                if (userJob.getScore().equals(job.getScore())) {
                    vo.setIsRight(true);
                }
            } else {
                vo.setIsRight(false);
            }
            submitVos.add(vo);
        }

        //未提交集合
        ArrayList<UserJobVo> notSubmitVos = new ArrayList<>();
        List<UserJob> notSubmitUserJobs = userJobDao.createLambdaQuery().andEq(UserJob::getJobId, jobId).andEq(UserJob::getClassId, classId).andIn(UserJob::getUserId, userIds).andEq(UserJob::getStatus, 0).andEq(UserJob::getIsDeleted, false).select();
        for (UserJob userJob : notSubmitUserJobs) {
            ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getUserId, userJob.getUserId()).andEq(ClassMembers::getIsDeleted, false).single();
            UserJobVo vo = new UserJobVo();
            vo.setId(userJob.getId());
            vo.setJobId(userJob.getJobId());
            vo.setUserId(single.getUserId());
            vo.setUserName(single.getNickname());
            if (single.getHeadImage() != null) {
                vo.setHeadImage(single.getHeadImage());
            } else {
                User unique = userDao.unique(single.getUserId());
                vo.setHeadImage(unique.getHeadImage());
            }
            vo.setStatus(userJob.getStatus());
            vo.setComment(userJob.getComment());
            vo.setScore(userJob.getScore());
            if (userJob.getFinishTime() != null) {
                vo.setFinishTime(format.format(userJob.getFinishTime()));
            }
            if (userJob.getScore() != null && job.getScore() != null) {
                if (userJob.getScore().equals(job.getScore())) {
                    vo.setIsRight(true);
                }
            } else {
                vo.setIsRight(false);
            }
            notSubmitVos.add(vo);
        }

        List<JobQuestion> jobQuestions = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, jobId).andEq(JobQuestion::getIsDeleted, false).select();
        BigDecimal zScore = new BigDecimal(0);
        for (JobQuestion jobQuestion : jobQuestions) {
            Question question = questionDao.unique(jobQuestion.getQuestionId());
            zScore = zScore.add(question.getScore());
        }

        //全对集合
        ArrayList<UserJobVo> allRightVos = new ArrayList<>();
        //未全对集合
        ArrayList<UserJobVo> notAllRightVos = new ArrayList<>();

        for (UserJob userJob : submitUserJobs) {
            ClassMembers single = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getUserId, userJob.getUserId()).andEq(ClassMembers::getIsDeleted, false).single();
            if (userJob.getScore().compareTo(zScore) == 0) {
                UserJobVo vo = new UserJobVo();
                vo.setId(userJob.getId());
                vo.setJobId(userJob.getJobId());
                vo.setUserId(single.getUserId());
                vo.setUserName(single.getNickname());
                if (single.getHeadImage() != null) {
                    vo.setHeadImage(single.getHeadImage());
                } else {
                    User unique = userDao.unique(single.getUserId());
                    vo.setHeadImage(unique.getHeadImage());
                }
                vo.setStatus(userJob.getStatus());
                vo.setComment(userJob.getComment());
                vo.setScore(userJob.getScore());
                if (userJob.getFinishTime() != null) {
                    vo.setFinishTime(format.format(userJob.getFinishTime()));
                }
                if (userJob.getScore() != null && job.getScore() != null) {
                    if (userJob.getScore().equals(job.getScore())) {
                        vo.setIsRight(true);
                    }
                } else {
                    vo.setIsRight(false);
                }
                allRightVos.add(vo);
            }
            if (userJob.getScore().compareTo(zScore) == -1) {
                UserJobVo vo = new UserJobVo();
                vo.setId(userJob.getId());
                vo.setJobId(userJob.getJobId());
                vo.setUserId(single.getUserId());
                vo.setUserName(single.getNickname());
                if (single.getHeadImage() != null) {
                    vo.setHeadImage(single.getHeadImage());
                } else {
                    User unique = userDao.unique(single.getUserId());
                    vo.setHeadImage(unique.getHeadImage());
                }
                vo.setStatus(userJob.getStatus());
                vo.setComment(userJob.getComment());
                vo.setScore(userJob.getScore());
                if (userJob.getFinishTime() != null) {
                    vo.setFinishTime(format.format(userJob.getFinishTime()));
                }
                if (userJob.getScore() != null && job.getScore() != null) {
                    if (userJob.getScore().equals(job.getScore())) {
                        vo.setIsRight(true);
                    }
                } else {
                    vo.setIsRight(false);
                }
                notAllRightVos.add(vo);
            }
        }
        GetAllStudentListDto studentListDto = new GetAllStudentListDto();
        studentListDto.setAllList(allVos);
        studentListDto.setSubmitList(submitVos);
        studentListDto.setNotSubmitList(notSubmitVos);
        studentListDto.setAllRightList(allRightVos);
        studentListDto.setNotRightList(notAllRightVos);

        return GlobalReponse.success(studentListDto);
    }

    /**
     * 老师添加评语
     *
     * @param userJobId
     * @param remark
     * @return
     */
    @Override
    public GlobalReponse addRemark(Long userJobId, String remark, Long userId) {
        UserJob userJob = userJobDao.unique(userJobId);
        userJob.setComment(remark);
        userJob.setUpdateBy(userId.toString());
        userJob.setUpdateTime(new Date());
        userJobDao.updateTemplateById(userJob);
        return GlobalReponse.success("评价成功");
    }


    /**
     * 查询学生个人答题记录
     *
     * @param jobId
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<StudentAnswerVoList> getStudentAnswer(Long jobId, Long userId, Long classId) {
        Job job = jobDao.unique(jobId);
        User unique = userDao.unique(job.getCreateBy());
        UserJob userJob = userJobDao.createLambdaQuery().andEq(UserJob::getClassId, classId).andEq(UserJob::getJobId, jobId).andEq(UserJob::getUserId, userId).single();
        List<JobQuestion> list = jobQuestionDao.createLambdaQuery().andEq(JobQuestion::getClassJobId, jobId).andEq(JobQuestion::getIsDeleted, false).select();
        ArrayList<StudentAnswerVo> vos = new ArrayList<>();
        for (JobQuestion jobQuestion : list) {
            StudentAnswerVo vo = new StudentAnswerVo();
            QuestionRecord single = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getClassId, userJob.getClassId()).andEq(QuestionRecord::getQuestionId, jobQuestion.getQuestionId()).andEq(QuestionRecord::getUserId, userId).andEq(QuestionRecord::getJobId, jobId).andEq(QuestionRecord::getIsDeleted, false).single();
            if (single != null) {
                Question question = questionDao.unique(single.getQuestionId());
                vo.setQuestionId(jobQuestion.getQuestionId());
                vo.setType(question.getType());
                vo.setSerialNumber(jobQuestion.getSerialNumber());
                if (single.getScore() != null && single.getScore().compareTo(BigDecimal.ZERO) > 0) {
                    vo.setIsRight(true);
                } else {
                    vo.setIsRight(false);
                }
                vo.setIsCheck(single.getIsCheck());
                vo.setIsAnswer(true);
                vo.setScore(single.getScore());
                vo.setTime(single.getUseTime() * 1000L);
                vos.add(vo);
            } else {
                Question question = questionDao.unique(jobQuestion.getQuestionId());
                vo.setQuestionId(jobQuestion.getQuestionId());
                vo.setType(question.getType());
                vo.setSerialNumber(jobQuestion.getSerialNumber());
                vo.setIsAnswer(false);
                vos.add(vo);
            }
        }
        StudentAnswerVoList voList = new StudentAnswerVoList();
        voList.setUserJobId(userJob.getId());
        voList.setTeacherHeadImage(unique.getHeadImage());
        voList.setComment(userJob.getComment());
        if (userJob.getScore() == null) {
            voList.setScore(new BigDecimal(0));
        } else {
            voList.setScore(userJob.getScore());
        }
        if (userJob.getUseTime() == null) {
            voList.setTime(0L);
        } else {
            voList.setTime(userJob.getUseTime() * 1000L);
        }
        User student = userDao.unique(userId);
        ClassMembers classMembers = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, userJob.getClassId()).andEq(ClassMembers::getUserId, userId).andEq(ClassMembers::getIsDeleted, false).single();
        if (classMembers != null) {
            if (classMembers.getNickname() != null) {
                voList.setName(classMembers.getNickname());
            } else {
                voList.setName(student.getName());
            }
            if (classMembers.getHeadImage() != null) {
                voList.setHeadImage(classMembers.getHeadImage());
            } else {
                voList.setHeadImage(student.getHeadImage());
            }
        } else {
            voList.setName(student.getName());
            voList.setHeadImage(student.getHeadImage());
        }
        voList.setList(vos);
        return GlobalReponse.success(voList);
    }

    /**
     * 给学生打分
     *
     * @param dto
     * @param teacherId
     * @return
     */
    @Override
    public GlobalReponse pullStudentScore(PullStudentScoreDto dto, Long teacherId) {
        QuestionRecord record = new QuestionRecord();
        record.setIsDeleted(false);
        record.setClassId(dto.getClassId());
        record.setUserId(dto.getUserId());
        record.setQuestionId(dto.getQuestionId());
        record.setJobId(dto.getJobId());
        QuestionRecord templateOne = questionRecordDao.templateOne(record);
        templateOne.setScore(dto.getScore());
        templateOne.setUpdateTime(new Date());
        templateOne.setIsCheck(true);
        templateOne.setUpdateBy(teacherId.toString());
        questionRecordDao.updateTemplateById(templateOne);
        List<QuestionRecord> select = questionRecordDao.createLambdaQuery().andEq(QuestionRecord::getClassId, dto.getClassId()).andEq(QuestionRecord::getJobId, dto.getJobId()).andEq(QuestionRecord::getUserId, dto.getUserId()).andEq(QuestionRecord::getIsDeleted, false).select();
        List<Boolean> collect = select.stream().map(QuestionRecord::getIsCheck).collect(Collectors.toList());
        UserJob userJob = userJobDao.createLambdaQuery().andEq(UserJob::getClassId, dto.getClassId()).andEq(UserJob::getJobId, dto.getJobId()).andEq(UserJob::getUserId, dto.getUserId()).andEq(UserJob::getIsDeleted, false).single();
        if (userJob.getScore() == null) {
            userJob.setScore(dto.getScore());
        } else {
            userJob.setScore(userJob.getScore().add(dto.getScore()));
        }
        if (!collect.contains(false)) {
            userJob.setStatus(2);
        }
        userJob.setUpdateBy(teacherId.toString());
        userJob.setUpdateTime(new Date());
        userJobDao.updateTemplateById(userJob);
        return GlobalReponse.success("打分成功");
    }

    /**
     * 催交作业
     *
     * @param jobId
     * @param studentId
     * @param teacherId
     * @return
     */
    @Override
    public GlobalReponse callHomeWork(Long jobId, Long studentId, Long teacherId) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        Job job = jobDao.unique(jobId);
        JobBack single = jobBackDao.createLambdaQuery().andEq(JobBack::getJobId, jobId).andEq(JobBack::getUserId, studentId).andEq(JobBack::getStatus, 0).andEq(JobBack::getIsDeleted, false).single();
        Date date = new Date();
        if (single != null) {
            if ((date.getTime() - single.getRiseTime().getTime()) % nd % nh / nm < 1L) {
                return GlobalReponse.success("不可重复点击，请稍后再发起催交");
            }
            JobBackDeleted jobBackDeleted = jobBackDeletedDao.createLambdaQuery().andEq(JobBackDeleted::getJobBackId, single.getId()).andEq(JobBackDeleted::getUserId, single.getUserId()).andEq(JobBackDeleted::getIsDeleted, false).single();
            if (jobBackDeleted != null) {
                jobBackDeleted.setIsRead(0);
                jobBackDeletedDao.updateTemplateById(jobBackDeleted);
            }
            single.setRiseTime(date);
            single.setUpdateTime(date);
            single.setUpdateBy(teacherId.toString());
            jobBackDao.updateTemplateById(single);
            return GlobalReponse.success("催交提醒已发送，1分钟后可再次发送催交提醒");
        }
        JobBack jobBack = new JobBack();
        jobBack.setUserId(studentId);
        jobBack.setJobId(jobId);
        jobBack.setStatus(0);
        jobBack.setRiseTime(new Date());
        jobBack.setIsDeleted(false);
        jobBack.setCreateBy(teacherId.toString());
        jobBack.setCreateTime(new Date());
        jobBackDao.insertTemplate(jobBack);
        return GlobalReponse.success("催交提醒已发送，1分钟后可再次发送催交提醒");
    }
}
